Python datetime, Explained Properly: Time Zones, Timestamps, Daylight Saving Time, and the Two Traps Everyone Hits
Dates and times are easy to get wrong: the wrong time zone, a day off, or mixing naive and aware datetimes. This guide covers the datetime module from scratch — date, time, datetime, timedelta, time zones with ZoneInfo, strftime/strptime, timestamps, daylight saving time, and calendar math — with a small class schedule as its demo. Standard library only, Python 3.12.3, every output a real measured run.

Dates and times show up in every Python program, and they are among the easiest things to get wrong: storing a time in the wrong time zone, being a day off, or subtracting a time that has no time zone from one that does. Python's datetime module handles all of this: date for dates, time for times of day, datetime for the two combined, timedelta for the difference between two times, and zoneinfo for time zones. This guide explains the whole set from scratch, using a fictional class schedule and meeting planner as its scenario (dates and times are demo data). All code uses only the Python standard library, was actually run on Python 3.12.3, and every output quoted is a real measured result. To keep the output reproducible, every demo uses a fixed time — 23 November 2026 — rather than "now".
The most important sentence goes first, and it is the distinction the official documentation opens with: date and time objects come in two kinds, "aware" (with time zone information) and "naive" (without it). An aware object can say exactly which moment it is; a naive object does not know which time zone it belongs to — whether it represents UTC, local time, or something else is entirely up to the program. Almost every hard bug in the datetime module comes from mixing the two. Keep that distinction in mind and the rest of this guide will make sense.
Three basic types: date, time, datetime
The three most-used classes in the datetime module have a clean division of labor: date holds only year, month, and day; time holds only hour, minute, and second; datetime combines both. Start with the basics — creating them and reading their parts:
from datetime import date, time, datetime
d = date(2026, 11, 23)
print("d =", d, "weekday (0=Monday):", d.weekday())
print("year/month/day:", d.year, d.month, d.day)
t = time(15, 30, 0)
print("t =", t, "hour/minute/second:", t.hour, t.minute, t.second)
dt = datetime(2026, 11, 23, 15, 30, 0)
print("dt =", dt)
print("dt.isoformat() =", dt.isoformat())
Output:
d = 2026-11-23 weekday (0=Monday): 0
year/month/day: 2026 11 23
t = 15:30:00 hour/minute/second: 15 30 0
dt = 2026-11-23 15:30:00
dt.isoformat() = 2026-11-23T15:30:00
Three details are worth pausing on. First, weekday() returns 0 for Monday and 6 for Sunday; 23 November 2026 happens to be a Monday, so it returns 0. There is also isoweekday(), which returns 1 for Monday and 7 for Sunday — the only difference is whether numbering starts at 0 or 1, so do not mix them up. Second, isoformat() produces an ISO 8601 string with the letter T between the date and the time; it is the standard format for exchanging times between systems, and the one to use for databases, logs, and APIs. Third, objects of all three classes are immutable: you cannot assign dt.hour = 16; to change a value you use replace() to build a new object — a method the time-zone section below comes back to.
timedelta: adding and subtracting time
To compute "what date is seven days from now" or "how many days between two dates", use timedelta — it represents a duration, not a moment:
from datetime import timedelta
print("dt + 7 days =", dt + timedelta(days=7))
print("dt + 90 minutes =", dt + timedelta(minutes=90))
print("dt - 3 hours =", dt - timedelta(hours=3))
christmas = date(2026, 12, 25)
print("Christmas - today =", christmas - d, "i.e.", (christmas - d).days, "days")
week = timedelta(weeks=1)
print("One week =", week, "total seconds =", week.total_seconds())
Output:
dt + 7 days = 2026-11-30 15:30:00
dt + 90 minutes = 2026-11-23 17:00:00
dt - 3 hours = 2026-11-23 12:30:00
Christmas - today = 32 days, 0:00:00 i.e. 32 days
One week = 7 days, 0:00:00 total seconds = 604800.0
A datetime plus a timedelta gives a new datetime; two date objects subtracted give a timedelta. Note how "Christmas - today" prints as 32 days, 0:00:00 — a timedelta's string form is just "days, hours, minutes, seconds" joined together. One more thing is easy to trip over: the internal representation of a negative timedelta looks wrong at first:
print("Note: timedelta(-1 hour) is stored internally as", timedelta(hours=-1))
Output:
Note: timedelta(-1 hour) is stored internally as -1 day, 23:00:00
Minus one hour shows up as "-1 day plus 23 hours", because a timedelta stores only three numbers internally (days, seconds, microseconds) and requires seconds and microseconds to be non-negative, so -1 hour is stored as "-1 day + 86,340 seconds". The value is correct (-86,400 + 86,340 = -3,600 seconds), it just looks alarming. The official documentation flags this too, and suggests a small helper that prints a negative duration as -(1:00:00) instead. Two rules cover everyday use: get the total seconds with total_seconds(), and never assemble it yourself from .days and .seconds — .seconds is only the within-a-day part, not the total, and assembling it by hand will be off by whole days.
Time zones: one instant, three local times
Time zones are the most useful part of datetime and also the easiest to get confused by. Start with the most direct example: one instant, shown in three places.
from datetime import timezone
from zoneinfo import ZoneInfo
utc_noon = datetime(2026, 11, 23, 12, 0, 0, tzinfo=timezone.utc)
print("UTC:", utc_noon, "->", utc_noon.strftime("%Y-%m-%d %H:%M"))
shanghai = utc_noon.astimezone(ZoneInfo("Asia/Shanghai"))
print("Shanghai:", shanghai.strftime("%Y-%m-%d %H:%M %Z"))
tokyo = utc_noon.astimezone(ZoneInfo("Asia/Tokyo"))
print("Tokyo:", tokyo.strftime("%Y-%m-%d %H:%M %Z"))
los_angeles = utc_noon.astimezone(ZoneInfo("America/Los_Angeles"))
print("Los Angeles:", los_angeles.strftime("%Y-%m-%d %H:%M %Z"))
Output:
UTC: 2026-11-23 12:00:00+00:00 -> 2026-11-23 12:00
Shanghai: 2026-11-23 20:00 CST
Tokyo: 2026-11-23 21:00 JST
Los Angeles: 2026-11-23 04:00 PST
Noon UTC is 8 p.m. in Shanghai, 9 p.m. in Tokyo, and 4 a.m. in Los Angeles — one instant, four ways of writing it. Two things do the work: timezone.utc is Python's built-in UTC time zone, and ZoneInfo("Asia/Shanghai") reads the Shanghai time zone from the system's built-in IANA time zone database. astimezone() means "show this same instant in another time zone": the instant itself does not change, only the clock reading changes. Note that Los Angeles shows PST (Pacific Standard Time), not PDT: 23 November 2026 is past the end of daylight saving time, so the US West Coast is on standard time, UTC-8 — the daylight saving switch is handled automatically by ZoneInfo, with no arithmetic needed from you.

One more thing about ZoneInfo: it joined the standard library in Python 3.9, and its time zone data comes from the operating system's IANA database. Linux and macOS normally ship it; on Windows, if the system has no time zone data, the extra tzdata package is needed — a supplement outside the standard library, not required for this guide's demos. The older approach used the third-party library pytz; new code should always use zoneinfo and not learn pytz's conventions.
strftime and strptime: formatting and parsing
To show a time object to a person, or to read one back from a string, use the pair strftime (format) and strptime (parse):
print('dt.strftime("%Y-%m-%d %H:%M") =', dt.strftime("%Y-%m-%d %H:%M"))
print('dt.strftime("%A") =', dt.strftime("%A"))
parsed = datetime.strptime("2026-11-23 15:30", "%Y-%m-%d %H:%M")
print('strptime("2026-11-23 15:30") =', parsed)
print("Does the parsed value equal dt?", parsed == dt)
Output:
dt.strftime("%Y-%m-%d %H:%M") = 2026-11-23 15:30
dt.strftime("%A") = Monday
strptime("2026-11-23 15:30") = 2026-11-23 15:30:00
Does the parsed value equal dt? True
Format codes are the one part of this you will keep looking up, and the common ones are few: %Y is the four-digit year, %m the month (01–12), %d the day (01–31), %H the hour in 24-hour time (00–23), %M the minute, %S the second, %A the full weekday name (Monday), %Z the time zone name (CST, JST, PST). The full table has a whole section in the official documentation; there is no need to memorize it, just to know where to look.
Parsing needs care in two ways. First, the format string has to match the input string exactly — one character off and it raises:
try:
datetime.strptime("2026-13-01", "%Y-%m-%d")
except ValueError as e:
print('strptime("2026-13-01") raises: ValueError', e)
Output:
strptime("2026-13-01") raises: ValueError time data '2026-13-01' does not match format '%Y-%m-%d'
There is no 13th month, so parsing raises a ValueError — which is a good thing: bad data is stopped at the door instead of quietly becoming a wrong time. Second, what strptime returns is naive: it carries no time zone information. If the input string itself carries a time zone (such as the +08:00 in an ISO-format string), use datetime.fromisoformat() instead — it reads the time zone part.
Timestamps: converting between datetime and numbers
A timestamp is another way to represent a time: a single float, the number of seconds since 1 January 1970, 00:00:00 UTC. Databases, logs, and APIs often pass times as timestamps, because a number has no formatting questions attached:
aware = datetime(2026, 11, 23, 12, 0, 0, tzinfo=timezone.utc)
ts = aware.timestamp()
print("aware.timestamp() =", ts)
print("datetime.fromtimestamp(ts, tz=timezone.utc) =",
datetime.fromtimestamp(ts, tz=timezone.utc))
Output:
aware.timestamp() = 1795435200.0
datetime.fromtimestamp(ts, tz=timezone.utc) = 2026-11-23 12:00:00+00:00
timestamp() turns an aware object into a number; fromtimestamp() turns the number back into an aware object — round-trip, and the time is unchanged. Always pass the tz argument to fromtimestamp: without it, the timestamp is interpreted in the machine's local time zone, so the same code gives different results on different machines. A timestamp itself has no time zone; it only says "this many seconds since 1970". The time zone only matters when the timestamp is displayed as a clock time.
Trap one: naive and aware datetimes cannot be subtracted
This is the error beginners hit most often. Subtract a naive object from an aware one:
naive = datetime(2026, 11, 23, 15, 30, 0)
print("naive.tzinfo =", naive.tzinfo, " aware.tzinfo =", aware.tzinfo)
try:
print(aware - naive)
except TypeError as e:
print("aware - naive raises: TypeError", e)
Output:
naive.tzinfo = None aware.tzinfo = UTC
aware - naive raises: TypeError can't subtract offset-naive and offset-aware datetimes
The error message says it plainly: you cannot subtract "one that does not know its offset" from "one that does". A naive object's tzinfo is None; it does not know which moment it represents — 15:30 could be Shanghai's 15:30, UTC's 15:30, or something else. The aware object knows it is 12:00 UTC. Something that does not know what it is cannot be subtracted from something that does. There is only one fix: make both sides the same kind first — either make both aware (label the naive one with its correct time zone) or strip the time zone from both. The more thorough habit is to use aware objects (usually UTC) everywhere inside a program, and let naive objects appear only where a time zone genuinely does not matter, such as a pure date (a birthday, a deadline) — and for those, date alone is enough, without datetime at all.
Trap two: replace() relabels, it does not convert
The second trap is sneakier, because it does not raise an error — it just silently computes the wrong answer. Suppose you have a naive object, 2026-11-23 12:00, and you know it is actually a UTC time, and you want it as a Shanghai time. The intuitive code is replace(tzinfo=ZoneInfo("Asia/Shanghai")), and it is wrong:
utc_naive = datetime(2026, 11, 23, 12, 0, 0) # this 12:00 is actually a UTC time
wrong = utc_naive.replace(tzinfo=ZoneInfo("Asia/Shanghai"))
print("Wrong way, replace(tzinfo=Shanghai) =", wrong, "back in UTC that is",
wrong.astimezone(timezone.utc).strftime("%H:%M"))
right = utc_naive.replace(tzinfo=timezone.utc).astimezone(ZoneInfo("Asia/Shanghai"))
print("Right way, label UTC first, then astimezone =", right.strftime("%Y-%m-%d %H:%M %Z"))
Output:
Wrong way, replace(tzinfo=Shanghai) = 2026-11-23 12:00:00+08:00 back in UTC that is 04:00
Right way, label UTC first, then astimezone = 2026-11-23 20:00 CST
The wrong way keeps the 12:00 clock reading untouched and sticks a "Shanghai" label on it, so the instant it represents becomes 04:00 UTC — a full 8 hours off, with no error raised anywhere. The right way takes two steps: first label it with replace(tzinfo=timezone.utc) to tell Python "this 12:00 is a UTC time", then convert it with astimezone() to Shanghai time, giving 8 p.m. Remember the rule: replace only changes the label, not the instant; astimezone actually converts. Every time you see replace(tzinfo=...), ask one more question: "which time zone was this moment originally in?" If you cannot answer, that line is probably wrong.
A complete example: what time is next Monday's class
Now put everything together in one complete example: today is Monday, 23 November 2026, and there is a class next Monday at 7 p.m. Shanghai time. What time is that in UTC and in Los Angeles?
today = date(2026, 11, 23) # a Monday
next_monday = today + timedelta(weeks=1)
lesson = datetime.combine(next_monday, time(19, 0, 0), tzinfo=ZoneInfo("Asia/Shanghai"))
print("Today:", today, "a", ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"][today.weekday()])
print("Next Monday's class (Shanghai):", lesson.strftime("%Y-%m-%d %H:%M %Z"))
print("Same instant in UTC:", lesson.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M %Z"))
print("Same instant in Los Angeles:", lesson.astimezone(ZoneInfo("America/Los_Angeles")).strftime("%Y-%m-%d %H:%M %Z"))
Output:
Today: 2026-11-23 a Monday
Next Monday's class (Shanghai): 2026-11-30 19:00 CST
Same instant in UTC: 2026-11-30 11:00 UTC
Same instant in Los Angeles: 2026-11-30 03:00 PST
This example uses one method not covered before: datetime.combine(), which joins a date and a time into a datetime, with a third argument that can carry a time zone. The example walks the full correct flow: compute the day with date arithmetic (next Monday), assemble the aware moment with combine, then convert it with astimezone for people in different places. Los Angeles gets 3 a.m. — and that time is itself part of the answer: if your class has students in Los Angeles, they are unlikely to make it at that hour, and rescheduling matters more than converting.
Daylight saving time: the two hardest days of the year
The hardest part of time zones is daylight saving time. Twice a year the clock "jumps": on the day daylight saving starts, 2 a.m. jumps straight to 3 a.m., and the times between 2 and 3 simply do not exist; on the day it ends, 1 a.m. to 2 a.m. happens twice. Take New York in 2026:
ny = ZoneInfo("America/New_York")
# US daylight saving time starts 8 March 2026: 2 a.m. jumps straight to 3 a.m., so 2:30 does not exist
spring = datetime(2026, 3, 8, 2, 30, 0, tzinfo=ny)
print("2026-03-08 02:30 (New York) is actually:", spring.strftime("%H:%M %Z"),
"UTC offset", spring.utcoffset().total_seconds() / 3600, "hours")
Output:
2026-03-08 02:30 (New York) is actually: 02:30 EST UTC offset -5.0 hours
A nonexistent time does not raise an error; Python silently interprets it with the pre-transition offset (EST, -5 hours).
2:30 a.m. on 8 March 2026 does not exist in New York — the clock jumped from 2 to 3. But Python does not raise an error; it silently interprets the time with the pre-transition offset (EST, UTC-5). That is the most dangerous kind of mistake: the program runs normally, the result looks normal, but the instant it represents is wrong. When handling times from external input, if the input falls in a daylight-saving gap, verify that the moment exists instead of trusting it blindly.
The autumn case is the mirror image: the same clock time happens twice:
# Daylight saving time ends 1 November 2026: 1 a.m. to 2 a.m. happens twice
fall_first = datetime(2026, 11, 1, 1, 30, 0, tzinfo=ny, fold=0)
fall_second = datetime(2026, 11, 1, 1, 30, 0, tzinfo=ny, fold=1)
print("2026-11-01 01:30 (first time):", fall_first.strftime("%H:%M %Z"),
"UTC offset", fall_first.utcoffset().total_seconds() / 3600, "hours")
print("2026-11-01 01:30 (second time):", fall_second.strftime("%H:%M %Z"),
"UTC offset", fall_second.utcoffset().total_seconds() / 3600, "hours")
print("Subtracted directly:", fall_second - fall_first)
print("Converted to UTC first, then subtracted:",
fall_second.astimezone(timezone.utc) - fall_first.astimezone(timezone.utc))
Output:
2026-11-01 01:30 (first time): 01:30 EDT UTC offset -4.0 hours
2026-11-01 01:30 (second time): 01:30 EST UTC offset -5.0 hours
Subtracted directly: 0:00:00
Converted to UTC first, then subtracted: 1:00:00
The two 01:30s are one in daylight time (EDT, UTC-4) and one in standard time (EST, UTC-5), a real hour apart. But subtracting them directly gives 0:00:00 — because both objects share the same tzinfo, ZoneInfo("America/New_York"), and Python ignores the offsets and subtracts the clock readings when the time zones match. That behavior is documented, not a bug, but it is very easy to trip over. The correct calculation converts both times to UTC first, giving the true 1:00:00. The fold parameter is what separates the two occurrences: fold=0 is the first (daylight time), fold=1 is the second (standard time). In everyday development, scheduled jobs, meetings, and log timestamps in those two hours around a daylight-saving switch deserve a separate check — many "once a year" production incidents start right there.
Calendar math: first day, last day, days in a month
Beyond adding and subtracting moments, the most common date calculations in everyday development are calendar-level: how many days are in this month, what weekday the 1st falls on, what date the 1st of next month is. The calendar module answers those most directly:
import calendar
print("Days in November 2026:", calendar.monthrange(2026, 11)[1])
print("Weekday of 1 November 2026 (0=Monday):", calendar.monthrange(2026, 11)[0])
print("Days in February 2026:", calendar.monthrange(2026, 2)[1])
first_dec = date(2026, 12, 1)
last_nov = date(2026, 11, calendar.monthrange(2026, 11)[1])
print("1 December 2026:", first_dec, "a", ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"][first_dec.weekday()])
print("Last day of November 2026:", last_nov, "a", ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"][last_nov.weekday()])
Output:
Days in November 2026: 30
Weekday of 1 November 2026 (0=Monday): 6
Days in February 2026: 28
1 December 2026: 2026-12-01 a Tuesday
Last day of November 2026: 2026-11-30 a Monday
monthrange(year, month) returns a tuple: the first number is the weekday of the 1st (0 = Monday, 6 = Sunday), the second is how many days the month has. 1 November 2026 is a Sunday (6), November has 30 days, and February 2026 has 28 — 2026 is not a leap year; the rule is "divisible by 4 but not by 100, unless also divisible by 400", and calendar.isleap(2026) returns False. The last day of a month is just "the month's day count" assembled into a date: date(2026, 11, monthrange(2026, 11)[1]) is 30 November. First days, last days, and quarter ends can all be built from monthrange plus timedelta, without hard-coding how many days each month has — hard-coding is guaranteed to break in February or in a leap year.
Quick reference: comparing, today, crossing a month boundary
A few high-frequency small questions, the kind that come up while writing code. First, compare two dates directly with <, >, and ==: date(2026, 11, 23) < date(2026, 12, 25) is True, and there is no need to convert to strings first — string comparison breaks on unpadded formats such as "2026-9-1" versus "2026-10-1", while date comparison is always right. Second, get "today" with date.today() and "now" with datetime.now(timezone.utc); date.today() returns today in the machine's local time zone, so a program running across time zones has to be aware of which machine's "today" it is getting. Third, adding a timedelta to a date crosses month boundaries automatically: date(2026, 11, 30) + timedelta(days=1) is 1 December, with no end-of-month logic needed from you. Fourth, isoformat() and fromisoformat() are a pair: the first turns an object into a string, the second turns the string back into an object, and a round trip loses no information — prefer that pair for logs, config files, and APIs over hand-assembled formats. Fifth, before subtracting two datetime objects, confirm that both are aware or both are naive; a mixed subtraction raises the error quoted above ("can't subtract offset-naive and offset-aware datetimes"), and that message already tells you what to fix.
Practical rules: store in UTC, convert to local time only for display
Finally, the practical rules, collected in one place. First, store times in UTC everywhere inside a program: database columns, log timestamps, times passed through APIs — all as UTC aware objects. UTC has no daylight saving time and no time zone switches, so it can never be wrong because "some place changed its daylight saving rules". Second, convert to local time only when showing a time to a user: call astimezone(ZoneInfo("Asia/Shanghai")) or similar at the last moment. Third, do not take "now" with a bare datetime.now() — it returns a naive object in the machine's local time zone, and the result changes when the code moves to another machine; use datetime.now(timezone.utc) to get an aware UTC object explicitly. Fourth, when only a date is needed, use date rather than a datetime with the time zeroed out — the type itself says "there is no time part here", which is more reliable than a comment. Fifth, when parsing a time string from outside, first confirm whether it carries a time zone: with one, use fromisoformat(); without one, find out "whose time zone is this" before deciding how to label it — a wrongly applied label costs 8 hours of error and raises no exception.
The hardest part of date and time handling was never the API itself; it is the question "which time zone is this time actually in?" Keep aware and naive apart, keep replace and astimezone apart, and keep storing apart from displaying, and the rest is lookup: format codes in the documentation, time zone names in the IANA list. This guide's demo code and output ship alongside the article; change them, run them, and they will teach more than memorizing a hundred rules.
One more piece of advice, about testing, worth its own paragraph: never assert against "now" in a time-related test. A test like assert datetime.now().hour == 15 passes once and fails once, purely by luck. The right approach is the one this guide's demos use: fixed times in tests, such as datetime(2026, 11, 23, 15, 30, tzinfo=timezone.utc), asserting that it converts to 20:00 in Shanghai and 04:00 in Los Angeles — numbers that never change, so the test never becomes unstable. If code genuinely needs "now", extract the "get now" step into a function that can be injected, and pass a fixed time in tests. Time is one of the easiest ways for a test to turn flaky, and fixed times are the cheapest fix.
Comments (0)
Sources
Related articles
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Port 8000 in code, 8080 in the config file, 9090 from the environment: each layer changes only its own keys, and the last one wins. Defaults plus INI plus env vars, bool('False') is True, and a missing key should fail at startup. Python 3.12.3 stdlib only.
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.