Python

Python Datetime — date, time, timedelta, and Formatting

Programs constantly answer three questions about time: what day is it, how far apart are two moments, and how should a moment be written down. The datetime module answers all three with a small set of types. A date holds a day, a time holds a clock reading, a datetime holds both, and a timedelta holds the distance between two of them. This guide builds each type, does arithmetic with it, formats and parses it, and attaches a time zone to it, with a small working program for each step and the exact output it prints.

Written November 12, 2026 · Tested with Python 3.12.3 · 13 min read

By the end of this guide
  • The main program: date and datetime hold fields
  • timedelta is the distance between two moments
  • strftime writes a value as text, strptime reads it back
  • A datetime is naive until it carries a time zone

Written November 12, 2026

Tested with Python 3.12.3

What this guide is

The datetime module works with four types. A date is a year, a month, and a day, and nothing else. A time is an hour, a minute, a second, and a microsecond count, with no day attached. A datetime pairs the two, so one value names one moment. A timedelta is a duration: the difference between two dates or two datetimes, stored as days, seconds, and microseconds. Every type is immutable. Arithmetic and conversion methods return new values and leave the original alone, the same rule tuples and strings follow. The sections below take the types in the order most code meets them: build a value, move it by a duration, write it as text and read it back, and give it a time zone.

The main program: date and datetime hold fields

Build a date from a year, a month, and a day, and a datetime from those three plus a clock time. Each part stays readable as its own attribute:

Python
from datetime import date, datetime

d = date(2026, 11, 12)
print(d)
print(d.year, d.month, d.day)
print(d.weekday())
print(d.strftime("%A"))
dt = datetime(2026, 11, 12, 16, 18, 30)
print(dt)
print(dt.date())
print(dt.time())
print(dt.isoformat())
print(dt.hour, dt.minute, dt.second)

The exact output:

Output
2026-11-12
2026 11 12
3
Thursday
2026-11-12 16:18:30
2026-11-12
16:18:30
2026-11-12T16:18:30
16 18 30

A date prints in the ISO form, year first, then month, then day, each padded to a fixed width. The weekday method counts Monday as zero, so Thursday comes back as 3; the strftime line right after turns the same day into its name, and the formatting section below covers that method in full. A datetime prints its date and its time joined by a space, and its date and time methods hand the two halves back as separate values. The isoformat method prints the same moment with a T between the halves, which is the form most files and APIs exchange. The last line reads the clock fields one by one, the way the second line read the calendar fields.

timedelta is the distance between two moments

A timedelta holds a duration, and adding one to a date or a datetime moves that value by the duration. Subtracting two values that share a type returns the timedelta between them:

Python
from datetime import date, datetime, timedelta

start = date(2026, 11, 12)
print(start + timedelta(days=7))
print(start - timedelta(weeks=2))
delta = datetime(2026, 11, 19, 12, 0) - datetime(2026, 11, 12, 9, 30)
print(delta)
print(delta.days, delta.seconds)
print(delta.total_seconds())
print(timedelta(hours=26))
print(timedelta(days=1, hours=2) == timedelta(hours=26))

The exact output:

Output
2026-11-19
2026-10-29
7 days, 2:30:00
7 9000
613800.0
1 day, 2:00:00
True

Adding seven days lands on the same weekday one week later, and subtracting two weeks walks back across the month boundary into October with no special handling. The gap between the two datetimes is seven days and two and a half hours. A timedelta stores that gap as a day count plus a second count inside the last day, which is why the seconds attribute prints 9000 and not the whole gap in seconds. The total_seconds method is the call that reports the whole duration as one number. A timedelta also normalizes its own arguments on the way in: 26 hours prints as one day and two hours, and the last line shows the two spellings compare equal because they store the same normalized value.

strftime writes a value as text, strptime reads it back

Formatting turns a date or a datetime into a string under your control. A format string mixes plain text with codes that start with a percent sign, and each code stands for one field:

Python
from datetime import datetime

dt = datetime(2026, 11, 12, 16, 18, 30)
print(dt.strftime("%Y-%m-%d"))
print(dt.strftime("%A, %B %d, %Y"))
print(dt.strftime("%I:%M %p"))
parsed = datetime.strptime("2026-11-12 16:18", "%Y-%m-%d %H:%M")
print(parsed)
print(parsed.strftime("%Y/%m/%d"))

The exact output:

Output
2026-11-12
Thursday, November 12, 2026
04:18 PM
2026-11-12 16:18:00
2026/11/12

The first format rebuilds the ISO date. The second spells the day and month names out, with %d padding the day of the month to two digits. The third switches to a twelve-hour clock: %I prints 04 for the hour that %H would print as 16, and %p prints PM. Parsing is the mirror image. The strptime method on the datetime class takes a string and the format that describes it, and returns the matching datetime; fields the string leaves out, here the seconds, start at zero. One format string therefore documents both directions, and code that writes dates with strftime and reads them with strptime stays consistent by construction. A format that does not match the string raises ValueError, so a bad input fails at the parse instead of passing silently as a wrong date.

A datetime is naive until it carries a time zone

A datetime built from plain fields has no time zone attached, and Python calls it naive: it names a wall-clock reading, not a fixed point in time. Passing tzinfo makes the value aware, and an aware value can convert between zones:

Python
from datetime import datetime, timedelta, timezone

utc_dt = datetime(2026, 11, 12, 16, 18, tzinfo=timezone.utc)
print(utc_dt)
print(utc_dt.isoformat())
west = timezone(timedelta(hours=-8), name="PST")
local_dt = utc_dt.astimezone(west)
print(local_dt)
print(local_dt.tzname())
print(local_dt.utcoffset().total_seconds() / 3600)
print(utc_dt == local_dt)
naive = datetime(2026, 11, 12, 16, 18)
print(naive.tzinfo)
print(utc_dt.tzinfo)

The exact output:

Output
2026-11-12 16:18:00+00:00
2026-11-12T16:18:00+00:00
2026-11-12 08:18:00-08:00
PST
-8.0
True
None
UTC

The timezone class builds a fixed offset from UTC. The utc member is the zero offset, and the west value here is a fixed eight hours behind it under the name PST. The astimezone method converts the UTC reading to that offset: the clock shows 08:18 instead of 16:18, and the equality test still returns True, because both values name the same moment. The last two lines state the naive and aware split directly: the plain datetime reports None for its tzinfo, and the aware one reports UTC. Arithmetic follows the same split. Subtracting a naive datetime from an aware one raises TypeError, so a program picks one kind at its boundary, usually by storing aware UTC values and converting to a local offset only to display them. A fixed offset never changes for daylight saving; a real place, whose offset shifts with the season, is described by the zoneinfo module instead, which reads the system time zone database.

replace changes fields, combine joins a date and a time

The replace method returns a copy with the named fields swapped and the original untouched. The combine method on the datetime class joins a separate date and time into one datetime:

Python
from datetime import date, datetime, time

print(date(2026, 12, 25) - date(2026, 11, 12))
d = date(2026, 11, 12)
print(d.replace(month=12, day=25))
print(d.replace(year=2027))
t = time(9, 30, 15)
print(t)
print(t.isoformat())
combined = datetime.combine(d, t)
print(combined)
print(combined.date())
print(combined.time())
print(date.min, date.max)

The exact output:

Output
43 days, 0:00:00
2026-12-25
2027-11-12
09:30:15
09:30:15
2026-11-12 09:30:15
2026-11-12
09:30:15
0001-01-01 9999-12-31

The first line is the subtraction from the timedelta section run on dates alone: the answer is a whole number of days, with a zero clock part. The two replace calls move the same starting date to a different day in the same year and to the same day one year later; each call names only the fields it changes, and d itself still holds November 12 for the combine below it. A time prints zero-padded, and its isoformat is the same text here because a plain clock time has no offset to show. Combine is the standard way to turn a picked day and a picked clock time, the two values a form usually collects, into the single datetime the rest of a program stores. The last line prints the ends of the date range itself: a date can name any day from January 1 of year 1 to December 31 of year 9999.

fromisoformat and timestamp round-trip a value

Two conversions cover most exchange with other systems. The fromisoformat method parses the text isoformat writes, and the timestamp method reports an aware datetime as seconds since the epoch:

Python
from datetime import datetime, timezone

dt = datetime.fromisoformat("2026-11-12T16:18:30")
print(dt)
print(datetime.fromisoformat("2026-11-12"))
aware = datetime(2026, 11, 12, 16, 18, 30, tzinfo=timezone.utc)
print(aware.timestamp())
back = datetime.fromtimestamp(aware.timestamp(), tz=timezone.utc)
print(back)
print(back == aware)

The exact output:

Output
2026-11-12 16:18:30
2026-11-12 00:00:00
1794500310.0
2026-11-12 16:18:30+00:00
True

A date-only string parses too, and its clock fields start at midnight. The timestamp counts seconds from January 1, 1970 in UTC, so the same moment gives the same number on any machine, and passing timezone.utc to fromtimestamp reads the number back in UTC and restores the original value exactly, as the last line shows. That pair is the safe way to store a moment as a plain number. Calling timestamp on a naive datetime instead treats the value as local time on the machine running the code, so the number then depends on where the program runs; attaching UTC first removes that dependence.

Dates compare, sort, and step

Dates and datetimes order by the moment they name, so the built-in comparisons, sorting, and min and max work on them directly. Adding one day at a time steps through a range:

Python
from datetime import date, timedelta

days = [date(2026, 11, 15), date(2026, 11, 12), date(2026, 11, 14)]
print([d.isoformat() for d in sorted(days)])
print(min(days), max(days))
print(date(2026, 11, 12) < date(2026, 11, 13))
start = date(2026, 11, 12)
week = [start + timedelta(days=i) for i in range(7)]
print(week[0], week[-1], len(week))
print([d.day for d in week])

The exact output:

Output
['2026-11-12', '2026-11-14', '2026-11-15']
2026-11-12 2026-11-15
True
2026-11-12 2026-11-18 7
[12, 13, 14, 15, 16, 17, 18]

Sorting three dates puts them in calendar order with no key function, because the comparison is built into the type. The week list steps from a start date by zero through six days, which is the shape most schedules, calendars, and report ranges take: pick a first day, add an offset per step, and let timedelta handle month and year boundaries when the range crosses one. Each generated day is a full date, so its own fields, its weekday, and its formatted form are all one method call away.

Which tool for which job

Job Tool Why
Hold a calendar day with no clock time date The value carries a year, a month, and a day, and nothing that can drift
Hold one moment datetime Date and clock fields live in one value that compares and sorts
Move a value by days or hours Add or subtract a timedelta The module handles month and year boundaries in the arithmetic
Measure the gap between two moments Subtract, then read days, seconds, or total_seconds total_seconds reports the whole gap as one number
Write a moment as text in your own layout strftime One format string picks the fields, the order, and the padding
Read text in a known layout strptime with the same format The format documents both directions, and a mismatch raises ValueError
Fix a moment to a point in time tzinfo with timezone.utc or a fixed offset An aware value converts between offsets and compares across them
Change one field of an existing value replace The method returns a changed copy and leaves the original alone
Join a picked day and a picked clock time datetime.combine The two form values become the single datetime a program stores
Exchange a moment as text or as a number isoformat with fromisoformat, or timestamp with fromtimestamp Both pairs round-trip, and the timestamp pair is exact for aware UTC values

Checklist

  • Before subtracting two datetimes, check that both are naive or both are aware; mixing the two raises TypeError.
  • Before reporting a gap with the seconds attribute, switch to total_seconds; seconds holds only the part inside the last day.
  • Before storing a moment as a timestamp, attach UTC first; a naive value is read as local time on the machine that runs the code.
  • Before adding days across a daylight saving change to an aware local value, remember a fixed offset never shifts; seasonal zones belong to zoneinfo.
  • Before parsing text with a hand-written format, read the value back with strftime under the same format on one known example.
  • Before formatting a day of the month for display, pick %d for the padded form or drop the padding code your platform uses for the bare number.

Sources

  • Python Standard Library, datetime — the date, time, datetime, timedelta, and timezone documentation this guide follows, including the strftime and strptime format codes and the naive and aware rules.
  • Python Standard Library, zoneinfo — the IANA time zone support the time zone section points to for places whose offset changes with the season.

Keep Exploring