Python Datetime Explained: Format, Parse and Handle Time Zones
Python datetime handles dates, times and durations, but naive times, format codes and daylight saving cause real bugs. Learn strftime, strptime, timedelta, ISO 8601 and zoneinfo with output from tested code, plus the traps to avoid.
- The Python datetime module gives you
date,time,datetime,timedeltaandtimezone. strftime()turns a datetime into text,strptime()turns text into a datetime, and the format must match exactly.- Store and compare times as aware UTC values. Python refuses to compare naive and aware datetimes.
- Use
zoneinfofor real time zones. On Windows, install thetzdatapackage first, or zone lookups fail.
Dates look simple until a report shows yesterday’s orders as today’s, a meeting reminder fires an hour late after the clocks change, or a log parser crashes on a date written the other way round. The Python datetime module has everything you need to avoid these bugs, as long as you know which tool to pick.
This guide walks through the module the way you use it at work: creating values, formatting and parsing, date arithmetic, time zones and timestamps. All output comes from Python 3.13.6 on our machine, with tzdata 2026.6 installed for zone data.
The main types
| Type | Holds | Example use |
|---|---|---|
date |
Year, month, day | Birthdays, due dates |
time |
Hour to microsecond | Opening hours |
datetime |
Date plus time, optional zone | Events, logs, orders |
timedelta |
A duration | “In 20 days”, time taken |
timezone |
A fixed UTC offset | UTC itself, fixed offsets |
Most code imports the classes directly: from datetime import datetime, date, timedelta, timezone. The module and the class share the name datetime, which causes the common error module 'datetime' has no attribute 'now'. If you write import datetime, you must call datetime.datetime.now().
Creating datetimes
from datetime import datetime, date, timedelta, timezone
d = datetime(2026, 11, 16, 9, 30)
print(d.isoformat(), d.tzinfo)
# 2026-11-16T09:30:00 None
The None matters: this value has no time zone. Python calls it naive. Other ways to get a datetime are datetime.now() for the local clock, datetime.now(timezone.utc) for the current UTC time with a zone attached, and date.today() for just the date.
Formatting with strftime
strftime() (string format time) builds text from a datetime using format codes:
print(d.strftime("%d %b %Y, %H:%M"), d.strftime("%A"))
# 16 Nov 2026, 09:30 Monday
The codes you will use most:
| Code | Meaning | Example |
|---|---|---|
%Y |
4-digit year | 2026 |
%m |
Month, zero padded | 11 |
%d |
Day, zero padded | 16 |
%H / %I |
Hour, 24h / 12h | 09 |
%M / %S |
Minute / second | 30 |
%p |
AM or PM | AM |
%b / %B |
Month name short / full | Nov / November |
%a / %A |
Weekday short / full | Mon / Monday |
%z |
UTC offset | +0000 |
A classic slip is mixing up %m (month) and %M (minute). Month and weekday names follow the current locale, so be careful when output must be machine-readable. In f-strings you can skip the method call: f"{d:%Y-%m-%d}" works too, as our f-strings guide shows.
Parsing with strptime
strptime() (string parse time) is the reverse. You describe the input format, and Python builds the datetime:
p = datetime.strptime("16/11/2026 18:05", "%d/%m/%Y %H:%M")
print(repr(p))
# datetime.datetime(2026, 11, 16, 18, 5)
datetime.strptime("2026-11-16", "%d/%m/%Y")
# ValueError: time data '2026-11-16' does not match format '%d/%m/%Y'
The match must be exact, including separators. That strictness is useful: wrap parsing of user input in try/except ValueError and show a clear message, as covered in our exception handling guide. Never guess between day-first and month-first formats. “03/04/2026” is March in one country and April in another.
ISO 8601: the format to default to
For anything stored or sent between systems, use ISO 8601. It sorts correctly as text, and Python reads it without a format string:
print(datetime.fromisoformat("2026-11-16T09:30:00+05:30"))
# 2026-11-16 09:30:00+05:30
isoformat() writes it and fromisoformat() reads it. Since Python 3.11, fromisoformat() accepts most ISO 8601 strings, including a trailing Z for UTC. JSON APIs nearly always use this format, so it pairs well with our Python JSON guide.
Date math with timedelta
A timedelta is a duration. Add it to a datetime to move forward, or subtract two datetimes to get one:
print(d + timedelta(days=20, hours=5))
# 2026-12-06 14:30:00
print(date(2026, 12, 25) - date(2026, 11, 16))
# 39 days, 0:00:00
shift = datetime(2026, 11, 16, 18, 0) - datetime(2026, 11, 16, 9, 30)
print(shift.total_seconds() / 3600)
# 8.5
Use total_seconds() to convert a duration into a plain number. The .seconds attribute is a trap: it only holds the seconds part left over after whole days, so a 2-day duration has .seconds == 0.
Naive vs aware datetimes
A naive datetime has no zone. An aware one carries a tzinfo, so it points to one exact moment. Python will not guess how they relate:
u = datetime(2026, 11, 16, 4, 0, tzinfo=timezone.utc)
print(d < u)
# TypeError: can't compare offset-naive and offset-aware datetimes
This error is a gift. It stops you from comparing “9:30 somewhere” with “4:00 UTC”. The fix is to make every datetime aware as early as possible, ideally the moment it enters your program.
Time zones with zoneinfo
The built-in timezone class only handles fixed offsets. Real places change offset for daylight saving, so use zoneinfo (standard since Python 3.9) with IANA names:
from zoneinfo import ZoneInfo
u = datetime(2026, 11, 16, 4, 0, tzinfo=timezone.utc)
print(u.astimezone(ZoneInfo("Asia/Kolkata")))
print(u.astimezone(ZoneInfo("America/New_York")))
# 2026-11-16 09:30:00+05:30
# 2026-11-15 23:00:00-05:00
The same moment is Monday morning in Kolkata and still Sunday night in New York. That is exactly why “today’s orders” reports go wrong when they use the server’s zone instead of the customer’s.
Windows tip: our first run failed with ZoneInfoNotFoundError: 'No time zone found with key Asia/Kolkata'. Windows has no system time zone database, so run pip install tzdata. Linux and macOS usually have zone data already.
The daylight saving trap
In New York, clocks jumped forward on 8 March 2026. Watch what adding one day does across that change:
ny = ZoneInfo("America/New_York")
a = datetime(2026, 3, 7, 12, tzinfo=ny)
b = a + timedelta(days=1)
print(b, b.utcoffset())
# 2026-03-08 12:00:00-04:00 -1 day, 20:00:00
The wall clock moved by exactly one day, to noon again, but the offset changed from -5 to -4 hours. Only 23 real hours passed. Python does wall-clock arithmetic within a zone. If you need exact elapsed time, convert to UTC, do the math there, and convert back for display.
Timestamps
A Unix timestamp counts seconds since 1 January 1970 UTC. Convert both ways with an explicit zone:
print(int(u.timestamp()))
# 1794801600
print(datetime.fromtimestamp(1794801600, tz=timezone.utc))
# 2026-11-16 04:00:00+00:00
Without tz=, fromtimestamp() returns naive local time, which differs from machine to machine. Also note that datetime.utcfromtimestamp() and datetime.utcnow() are deprecated because they return naive values that look like UTC but are not marked as such.
Adding months and years
timedelta has no months argument, because months have different lengths. Adding 30 days is not “one month later”:
print(date(2026, 1, 31) + timedelta(days=30))
# 2026-03-02
For calendar months, decide the business rule first. Does 31 January plus one month mean 28 February or 3 March? The third-party dateutil.relativedelta picks the last valid day, which suits most billing cases. Whatever you choose, write tests for month-end dates and 29 February.
Best practices
- Store UTC, display local. Keep aware UTC datetimes in databases and logs, and convert to the user’s zone only for display.
- Use ISO 8601 for text. It is unambiguous and sorts correctly.
- Use
datetime.now(timezone.utc), notutcnow(). - Use
zoneinfonames such asEurope/London, not fixed offsets, for real places. - Measure durations with
time.monotonic()when timing code, since the wall clock can jump. - Test the edges: month ends, leap days, DST changes and midnight. Our SQL date functions guide covers the database side.
Testing code that depends on the current time
Code that calls datetime.now() inside a function is hard to test, because the answer changes every second. The simplest fix needs no library: let the caller pass in the current time, and fall back to the real clock only when nothing is given.
from datetime import datetime, timezone
def is_overdue(due, now=None):
now = now or datetime.now(timezone.utc)
return now > due
due = datetime(2026, 11, 20, tzinfo=timezone.utc)
print(is_overdue(due, now=datetime(2026, 11, 19, tzinfo=timezone.utc))) # False
print(is_overdue(due, now=datetime(2026, 11, 21, tzinfo=timezone.utc))) # True
Both results came from our run. Tests can now check the day before, the day after and the exact boundary without waiting or mocking. When you cannot change the function signature, libraries such as freezegun and time-machine freeze the clock during a test, and our Python mocking guide shows how to patch datetime with unittest.mock. Whichever route you pick, put the tricky dates from the best practices list into a parametrized test so they run on every build.
Final thoughts
Python datetime is reliable once you follow a few rules. Format with strftime, parse with strptime or fromisoformat, use timedelta for durations, and keep every value aware, preferably in UTC. Reach for zoneinfo when people and places are involved, remember tzdata on Windows, and treat daylight saving as a test case rather than a surprise.
FAQ
What is the difference between strftime and strptime?
strftime formats a datetime object into a string. strptime parses a string into a datetime object using a format you describe.
How do I get the current time in UTC in Python?
Call datetime.now(timezone.utc). It returns an aware datetime marked as UTC. Avoid datetime.utcnow because it is deprecated and returns a naive value.
What is a naive datetime in Python?
A naive datetime has no time zone attached, so it does not point to one exact moment. Python refuses to compare it with an aware datetime.
How do I add months to a date in Python?
timedelta has no months argument. Use dateutil.relativedelta or write your own rule for month ends, and test dates such as 31 January.
Why does zoneinfo fail on Windows?
Windows does not ship the IANA time zone database that zoneinfo reads. Install the tzdata package with pip and the zone names will work.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.