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)Powered by
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)Powered by
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)Powered by
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)Powered by
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)Powered by
This builds a calendar date directly. Invalid values immediately raise an error, helping catch mistakes early.
from datetime import time
t = time(14,30,15)print(t)Powered by
This produces a time-of-day value. Use this when you don’t need the date attached.
from datetime import datetime
dt = datetime(2025,3,1,14,30)print(dt)Powered by
This creates a full timestamp. Adding a tzinfo argument makes it timezone-aware.
Creating from timestamps
Unix timestamps show up in logs, APIs, and operating systems. Python converts them easily to human-readable datetime objects.
datetime.fromtimestamp(1700000000)
datetime.utcfromtimestamp(1700000000)Powered by
The first interprets the timestamp in local time; the second interprets it in UTC.
Class methods for current values
When you need the current date or time, Python provides simple helpers. These are essential for logging, event tracking, and real-time pipelines.
from datetime import datetime, date, timezone
print(date.today())print(datetime.now())print(datetime.now(tz=timezone.utc))# Python 3.12+ preferredPowered by
These give you the current system time in either local time or UTC, depending on your needs.
datetime.fromtimestamp(1700000000)
datetime.utcfromtimestamp(1700000000)Powered by
These convert epoch timestamps into datetime objects. They’re extremely common when parsing API or database values.
Parsing from strings
Real-world datasets often store timestamps as text. Python provides reliable tools to convert those strings into structured values.
strptime()from datetime import datetime
dt = datetime.strptime("2025-03-01 14:30","%Y-%m-%d %H:%M")print(dt)Powered by
strptime() parses a string using a format pattern. If the string doesn’t match exactly, Python raises ValueError.
from datetime import datetime
dt = datetime.strptime("not-a-date","%Y-%m-%d")Powered by
This would fail because the input doesn’t match the expected pattern.
fromisoformat()
datetime.fromisoformat("2025-03-01T14:30:00")Powered by
ISO 8601 strings parse cleanly because the structure is standardized. This is often the easiest way to load timestamps from APIs or modern data pipelines.
Performing Date Arithmetic
Once you can create timestamps, the next step is working with them. You can do this by calculating durations, shifting dates, or comparing intervals.
Timedelta for temporal calculations
timedelta models fixed-duration periods like “5 hours” or “2 weeks.” These periods are useful for scheduling, logging, and if you need a simple countdown.
from datetime import datetime, timedelta
dt = datetime(2025,3,1,14,30)
new_dt = dt + timedelta(days=5)print(new_dt)Powered by
This example shifts the timestamp forward by five days.
start = datetime(2025,3,1,9,0)
end = datetime(2025,3,1,14,30)
duration = end - start
print(duration.total_seconds())Powered by
Here, subtracting two datetimes gives you a timedelta, which you can convert to seconds, days, or hours.
Fixed-duration vs. calendar-aware arithmetic
Not all units of time are equal. Months vary in length, years may have leap days, and end-of-month behavior can be unpredictable. For these scenarios, timedelta isn’t enough.
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.
This produces a time-of-day value. Use this when you don’t need the date attached.
This creates a full timestamp. Adding a
tzinfoargument makes it timezone-aware.Creating from timestamps
Unix timestamps show up in logs, APIs, and operating systems. Python converts them easily to human-readable datetime objects.
The first interprets the timestamp in local time; the second interprets it in UTC.
Class methods for current values
When you need the current date or time, Python provides simple helpers. These are essential for logging, event tracking, and real-time pipelines.
These give you the current system time in either local time or UTC, depending on your needs.
These convert epoch timestamps into
datetimeobjects. They’re extremely common when parsing API or database values.Parsing from strings
Real-world datasets often store timestamps as text. Python provides reliable tools to convert those strings into structured values.
strptime()parses a string using a format pattern. If the string doesn’t match exactly, Python raisesValueError.This would fail because the input doesn’t match the expected pattern.
ISO 8601 strings parse cleanly because the structure is standardized. This is often the easiest way to load timestamps from APIs or modern data pipelines.
Performing Date Arithmetic
Once you can create timestamps, the next step is working with them. You can do this by calculating durations, shifting dates, or comparing intervals.
Timedelta for temporal calculations
timedeltamodels fixed-duration periods like “5 hours” or “2 weeks.” These periods are useful for scheduling, logging, and if you need a simple countdown.This example shifts the timestamp forward by five days.
Here, subtracting two datetimes gives you a timedelta, which you can convert to seconds, days, or hours.
Fixed-duration vs. calendar-aware arithmetic
Not all units of time are equal. Months vary in length, years may have leap days, and end-of-month behavior can be unpredictable. For these scenarios,
timedeltaisn’t enough.