Working with dates and times looks simple until you start dealing with formats, time zones, daylight saving rules, or timestamps from multiple systems, at which point it's not an option to store time as raw strings or integers. Python’s datetime module exists to help you manage all of these moving parts in a predictable way.
This guide walks through the core classes, how to create and work with datetime objects, how to perform arithmetic, how to format and parse values, handle time zones, and more. Each section builds on the last, so you can move from basic operations to more advanced patterns.
Core Classes of the Python datetime Module
Before doing anything specific, it helps to understand how Python models dates and times at a conceptual level. The datetime module uses a small set of classes, each focused on one part of the problem. Knowing where each class fits makes the rest of the workflow much easier.
date
When you only need a calendar date without worrying about time of day or time zones, the date class is thing you need. It represents the year, month, and day using familiar attributes.
Here are the attributes:
year
month
day
And the methods:
today()
fromisoformat()
replace()
isoformat()
weekday()
isoweekday()
from datetime import date
d = date(2025,3,1)print(d)提供:
This code creates a simple calendar date. If you enter an invalid combination (like February 30), Python raises what is known as a ValueError.
time
Some tasks only care about the time of day, say, a reminder that runs at 2:30 PM. The time class would be helpful because it stores hours, minutes, seconds, and (not necessary for this example), microseconds or timezone data.
The attributes are: hour, minute, second, microsecond, tzinfo
The methods are: replace(), isoformat()
from datetime import time
t = time(14,30,15)print(t)提供:
This creates a clock time without a date attached. Invalid values (like hour=27) will generate an error.
datetime
Most real-world situations combine both date and time, and that’s where datetime comes in. It’s the most versatile class in the module and the one you’ll use most often for logging, processing, and coordinating events.
The attributes are (in addition to all the ones above): tzinfo
And the methods are now(), utcnow(), fromisoformat(), strptime(), strftime(), astimezone() It also support arithmetic with timedelta, which I'll cover in more detail.
from datetime import datetime
dt = datetime(2025,3,1,14,30)print(dt)提供:
This produces a complete timestamp with both date and time components.
timedelta
Whenever you need to measure elapsed time or shift a timestamp forward or backward, timedelta is the right choice. It represents a duration, not a specific moment.
The attributes are: days, seconds, microseconds. It's commonly used for offsets, time differences, and scheduling logic.
from datetime import timedelta
delta = timedelta(days=7, hours=3)print(delta)提供:
This represents a fixed-length duration. It becomes especially useful when added to or subtracted from a datetime.
tzinfo
tzinfo defines Python’s interface for time zones. You won’t create these directly, but the datetime system uses them whenever you attach or convert time zones.
timezone
timezone is a built-in tzinfo implementation for fixed UTC offsets like UTC or UTC+1. It’s useful for simple cases where daylight saving rules don’t matter.
Creating and Accessing Python datetime Objects
Once you know the classes, the next step is learning how to create instances of them. Python gives you several approaches depending on where your data comes from: manual entry, system time, timestamps, or text.
Using Class constructors
Constructors give you full control over the values you’re creating. This is often the most explicit and error-resistant way to build date, time, or datetime objects.
from datetime import date
d = date(2025,3,1)print(d)提供:
This builds a calendar date directly. Invalid values immediately raise an error, helping catch mistakes early.
Working with dates and times looks simple until you start dealing with formats, time zones, daylight saving rules, or timestamps from multiple systems, at which point it's not an option to store time as raw strings or integers. Python’s
datetimemodule exists to help you manage all of these moving parts in a predictable way.This guide walks through the core classes, how to create and work with
datetimeobjects, how to perform arithmetic, how to format and parse values, handle time zones, and more. Each section builds on the last, so you can move from basic operations to more advanced patterns.Core Classes of the Python datetime Module
Before doing anything specific, it helps to understand how Python models dates and times at a conceptual level. The
datetimemodule uses a small set of classes, each focused on one part of the problem. Knowing where each class fits makes the rest of the workflow much easier.date
When you only need a calendar date without worrying about time of day or time zones, the
dateclass is thing you need. It represents the year, month, and day using familiar attributes.Here are the attributes:
yearmonthdayAnd the methods:
today()fromisoformat()replace()isoformat()weekday()isoweekday()This code creates a simple calendar date. If you enter an invalid combination (like
February 30), Python raises what is known as aValueError.time
Some tasks only care about the time of day, say, a reminder that runs at 2:30 PM. The
timeclass would be helpful because it stores hours, minutes, seconds, and (not necessary for this example), microseconds or timezone data.The attributes are:
hour,minute,second,microsecond,tzinfoThe methods are:
replace(),isoformat()This creates a clock time without a date attached. Invalid values (like
hour=27) will generate an error.datetime
Most real-world situations combine both date and time, and that’s where
datetimecomes in. It’s the most versatile class in the module and the one you’ll use most often for logging, processing, and coordinating events.The attributes are (in addition to all the ones above):
tzinfoAnd the methods are
now(),utcnow(),fromisoformat(),strptime(),strftime(),astimezone()It also support arithmetic withtimedelta, which I'll cover in more detail.This produces a complete timestamp with both date and time components.
timedelta
Whenever you need to measure elapsed time or shift a timestamp forward or backward,
timedeltais the right choice. It represents a duration, not a specific moment.The attributes are:
days,seconds,microseconds. It's commonly used for offsets, time differences, and scheduling logic.This represents a fixed-length duration. It becomes especially useful when added to or subtracted from a datetime.
tzinfo
tzinfodefines Python’s interface for time zones. You won’t create these directly, but the datetime system uses them whenever you attach or convert time zones.timezone
timezoneis a built-intzinfoimplementation for fixed UTC offsets like UTC or UTC+1. It’s useful for simple cases where daylight saving rules don’t matter.Creating and Accessing Python datetime Objects
Once you know the classes, the next step is learning how to create instances of them. Python gives you several approaches depending on where your data comes from: manual entry, system time, timestamps, or text.
Using Class constructors
Constructors give you full control over the values you’re creating. This is often the most explicit and error-resistant way to build date, time, or datetime objects.
This builds a calendar date directly. Invalid values immediately raise an error, helping catch mistakes early.