Python Standard Library · Lesson 116 of 149

Python datetime and time

What you will learn

  • The types date, time, datetime and timedelta
  • Arithmetic and comparison of dates
  • Formatting (strftime) and parsing (strptime, fromisoformat)
  • Naive versus timezone-aware values, and UTC
  • The time module: timing and sleep
  • Common helpers: age, month end, weekdays

1. The types

The datetime module (the module has the same name as one of its types) offers:

Type Holds Example
date year, month, day date(2026, 3, 1)
time hour, minute, second, microsecond time(14, 30)
datetime a date and a time together datetime(2026, 3, 1, 14, 30, 45)
timedelta a length of time timedelta(days=2, hours=3)
timezone a fixed offset from UTC timezone.utc
from datetime import date, time, datetime, timedelta, timezone

2. Dates

d = date(2026, 3, 1)
print(d)
print(repr(d))
print(d.year, d.month, d.day)
print(d.weekday(), d.isoweekday())
2026-03-01
datetime.date(2026, 3, 1)
2026 3 1
6 7
  • weekday() counts Monday as 0 to Sunday as 6; isoweekday() counts Monday as 1 to Sunday as 7. The first of March 2026 is a Sunday.
  • Invalid dates are refused:
date(2026, 2, 30)
ValueError: day is out of range for month
  • date.today() gives today's date and datetime.now() the current date and time. Their values change every time you run the code, so the examples here use fixed dates.
Quick check: what are `weekday()` and `isoweekday()` for a Monday?

0 and 1.

3. Arithmetic with timedelta

Subtracting two dates gives a timedelta; adding a timedelta to a date gives a new date:

print(d + timedelta(days=30))
print(d - timedelta(weeks=2))
gap = date(2026, 12, 25) - d
print(gap)
print(gap.days)
print(d < date(2026, 3, 2), d == date(2026, 3, 1), max(d, date(2025, 1, 1)))
print(d.replace(day=31), d.replace(year=2028))
2026-03-31
2026-02-15
299 days, 0:00:00
299
True True 2026-03-01
2026-03-31 2028-03-01
  • timedelta accepts days, seconds, minutes, hours, weeks (and more). There is no months or years, because their lengths vary (section 8 shows a way).
  • Dates compare with <, == and max, and sort naturally.
  • replace makes a copy with some parts changed (dates are immutable).

Details of a timedelta:

td = timedelta(days=2, hours=3, minutes=30)
print(td, td.days, td.seconds, td.total_seconds())
print(td * 2, td / 2)
print(timedelta(hours=-1), abs(timedelta(hours=-1)))
2 days, 3:30:00 2 12600 185400.0
4 days, 7:00:00 1 day, 1:45:00
-1 day, 23:00:00 1:00:00

seconds is only the seconds left over after the days (12,600 = 3.5 hours). To get the whole length in one unit, use total_seconds() (185,400 here) and divide. Negative durations display in a strange form (-1 day, 23:00:00 means minus one hour), so print abs(...) or total_seconds() for readability.

4. Date and time together

dt = datetime(2026, 3, 1, 14, 30, 45)
print(dt)
print(dt.hour, dt.minute, dt.second)
print(dt.date(), dt.time())
print(dt + timedelta(hours=10))
print(dt - datetime(2026, 3, 1, 8, 0))
print((dt - datetime(2026, 2, 1)).total_seconds())
2026-03-01 14:30:45
14 30 45
2026-03-01 14:30:45
2026-03-02 00:30:45
6:30:45
2471445.0

dt.date() and dt.time() return the two parts (printed side by side on the third line). datetime.combine(date_value, time_value) builds one from the parts.

5. Formatting and parsing

Formatting a date or time as text uses strftime ("string from time") with codes:

Code Meaning Example
%Y / %y year (4 / 2 digits) 2026 / 26
%m / %d month / day, 2 digits 03 / 01
%B / %b month name, full / short March / Mar
%A / %a weekday name, full / short Sunday / Sun
%H / %I hour, 24-hour / 12-hour 14 / 02
%M / %S minute / second 30 / 45
%p AM or PM PM
%j day of the year 060
print(d.strftime("%A %d %B %Y"))
print(dt.strftime("%Y-%m-%d %H:%M"))
print(dt.strftime("%I:%M %p"))
print(d.strftime("%a %b %d, %y | %j"))
print(f"{dt:%d/%m/%Y}")
Sunday 01 March 2026
2026-03-01 14:30
02:30 PM
Sun Mar 01, 26 | 060
01/03/2026

An f-string can take the same codes after a colon (lesson 4.6). The names (March, Sunday) depend on your computer's language settings.

Parsing text into a date uses strptime ("string parse time") with the same codes:

print(datetime.strptime("2026-03-05 09:15", "%Y-%m-%d %H:%M"))
print(datetime.strptime("5 March 2026", "%d %B %Y").date())
datetime.strptime("2026/03/05", "%Y-%m-%d")
2026-03-05 09:15:00
2026-03-05
ValueError: time data '2026/03/05' does not match format '%Y-%m-%d'

If the text does not match the format exactly, you get a ValueError. For the standard ISO format (the safest way to store dates as text), use isoformat and fromisoformat:

print(date.fromisoformat("2026-03-05"))
print(datetime.fromisoformat("2026-03-05T09:15:00"))
print(dt.isoformat())
2026-03-05
2026-03-05 09:15:00
2026-03-01T14:30:45

Use ISO format (YYYY-MM-DD) when saving to files (lesson 15.7 needs dates as text) because it sorts correctly as plain text and has no ambiguity (is 03/05 March 5 or May 3?).

6. Time zones

A datetime without a time zone is naive: it is just numbers, with no idea of where on Earth. One with a zone is aware. The two cannot be mixed:

utc = datetime(2026, 3, 1, 12, 0, tzinfo=timezone.utc)
print(utc, utc.tzinfo)
print(utc.isoformat())

dhaka = timezone(timedelta(hours=6), "BST")
print(utc.astimezone(dhaka))
print(utc.astimezone(dhaka).strftime("%H:%M %Z"))

utc - dt
2026-03-01 12:00:00+00:00 UTC
2026-03-01T12:00:00+00:00
2026-03-01 18:00:00+06:00
18:00 BST
TypeError: can't subtract offset-naive and offset-aware datetimes
  • tzinfo=timezone.utc makes it aware, in UTC (Coordinated Universal Time, the world's reference time).
  • astimezone(zone) converts to another zone (same instant, different clock).
  • Aware values that mean the same moment are equal: the 12:00 UTC value equals 18:00 at offset +6.
  • Mixing naive and aware in arithmetic raises the TypeError above.

Fixed offsets cannot handle daylight saving changes. For real zones use zoneinfo (Python 3.9 and later), which knows the rules:

from zoneinfo import ZoneInfo

ny = utc.astimezone(ZoneInfo("America/New_York"))
print(ny, ny.tzname())

summer = datetime(2026, 7, 1, 12, 0, tzinfo=ZoneInfo("UTC")).astimezone(ZoneInfo("America/New_York"))
print(summer.tzname(), summer.utcoffset())
2026-03-01 07:00:00-05:00 EST
EDT -1 day, 20:00:00

New York is five hours behind UTC in winter (EST) and four hours in summer (EDT; the utcoffset of -1 day, 20:00:00 means minus four hours). On Windows you may need to install the tzdata package (python -m pip install tzdata, lesson 16.6) for ZoneInfo to work; it worked on the computer used here.

Good practice for programs: store and calculate in UTC (datetime.now(timezone.utc)), and convert to the user's zone only for display.

7. The time module

The time module works with plain numbers of seconds:

Function Use
time.time() seconds since 1 January 1970 UTC (the "epoch"), as a float
time.perf_counter() a high-precision clock for measuring durations
time.monotonic() a clock that never goes backwards
time.sleep(seconds) pause the program
import time

start = time.perf_counter()
time.sleep(0.05)
elapsed = time.perf_counter() - start
print(0.04 < elapsed < 0.5)
print(time.gmtime(0).tm_year, time.strftime("%Y", time.gmtime(0)))
True
1970 1970

Use perf_counter to time code (lesson 18.5), not time.time(), which can jump if the system clock is adjusted. time.sleep is used for pauses between retries (lesson 14.3) or to avoid overloading a server.

8. Handy recipes

Age (a birthday that has not yet come this year means one year less):

def age(born, on):
    return on.year - born.year - ((on.month, on.day) < (born.month, born.day))

print(age(date(2000, 5, 20), date(2026, 5, 19)))
print(age(date(2000, 5, 20), date(2026, 5, 20)))
25
26

(The tuple comparison (5, 19) < (5, 20) is True, which counts as 1.)

Month lengths and leap years with the calendar module:

import calendar

print(calendar.monthrange(2026, 2))
print(calendar.monthrange(2028, 2), calendar.isleap(2028), calendar.month_name[3])
(calendar.SUNDAY, 28)
(calendar.TUESDAY, 29) True March

monthrange returns the weekday of the 1st (6 is Sunday) and the number of days. Adding "one month" has no timedelta; the worked example builds it from these parts. Also notice what plain day arithmetic does at month ends: date(2026, 1, 31) + timedelta(days=30) is 2026-03-02.

Worked example: a payment schedule and a deadline

Payments fall on the same day of each month, but a day like the 31st must fall back to the last day of shorter months. Another function counts weekdays between two dates, and a deadline shows time left in several formats.

from datetime import date, datetime, timedelta
import calendar


def add_months(d, n):
    month_index = d.month - 1 + n
    year = d.year + month_index // 12
    month = month_index % 12 + 1
    day = min(d.day, calendar.monthrange(year, month)[1])
    return date(year, month, day)


def working_days(start, end):
    days, d = 0, start
    while d <= end:
        if d.weekday() < 5:
            days += 1
        d += timedelta(days=1)
    return days


start = date(2026, 1, 31)
for n in range(4):
    due = add_months(start, n)
    print(f"payment {n + 1}: {due:%a %d %b %Y}")

print("working days Mar 2-13:", working_days(date(2026, 3, 2), date(2026, 3, 13)))

deadline = datetime(2026, 3, 13, 17, 0)
now = datetime(2026, 3, 10, 9, 30)
left = deadline - now
print("time left:", left, "=", left.days, "days and", left.seconds // 3600, "hours")
print(f"{deadline:%d/%m/%Y %I:%M %p}")
print(datetime.strptime("13 Mar 2026 5:00PM", "%d %b %Y %I:%M%p") == deadline)
payment 1: Sat 31 Jan 2026
payment 2: Sat 28 Feb 2026
payment 3: Tue 31 Mar 2026
payment 4: Thu 30 Apr 2026
working days Mar 2-13: 10
time left: 3 days, 7:30:00 = 3 days and 7 hours
13/03/2026 05:00 PM
True
Step Idea
month_index // 12, % 12 month arithmetic that rolls over the year
min(d.day, monthrange(...)[1]) the 31st becomes the 28th in February and the 30th in April
weekday() < 5 Monday to Friday only (public holidays are not considered)
deadline - now a timedelta: days and seconds // 3600 split it into parts
strptime parses a human-style text back into the same value

The dates are made up. In real billing, check the rules of the contract: some use "last day of month", others "same day".

Common mistakes

  • Mixing naive and aware datetimes.
  • Using time.time() for measuring (use perf_counter).
  • Parsing with the wrong format string, or with ambiguous formats like 03/05/2026.
  • Expecting timedelta(months=1) (it does not exist).
  • Using timedelta.seconds as the total length (use total_seconds()).
  • Storing local times and being surprised by daylight saving; store UTC.
  • Using datetime.utcnow() (it returns a naive value and is discouraged; use datetime.now(timezone.utc)).
  • Testing code that depends on now() without being able to set the time.

Key takeaways

  • date, time, datetime and timedelta cover most needs; subtract dates to get a timedelta.
  • strftime formats, strptime parses, and isoformat / fromisoformat use the unambiguous YYYY-MM-DD form.
  • Naive and aware datetimes cannot be mixed; work in UTC and convert with astimezone or zoneinfo for display.
  • perf_counter times code; sleep pauses.
  • calendar.monthrange and tuple comparison solve month ends and ages.

Practice

1. How many days between 1 March 2026 and 25 December 2026?

Show answer

(date(2026, 12, 25) - date(2026, 3, 1)).days is 299.

2. Format datetime(2026, 3, 1, 14, 30) as 01/03/2026 02:30 PM.

Show answer

dt.strftime("%d/%m/%Y %I:%M %p")

3. Why does utc_value - naive_value raise a TypeError?

Show answer

One value knows its time zone and the other does not, so the difference would be meaningless. Make both aware or both naive.

4. What is the difference between td.seconds and td.total_seconds()?

Show answer

seconds is only the part left after whole days; total_seconds() is the entire duration in seconds.

5. Which clock should you use to measure how long a function takes?

Show answer

time.perf_counter() (subtract the start value from the end value).

6. Why save dates in files as 2026-03-05 rather than 03/05/2026?

Show answer

ISO format is unambiguous (no month/day confusion), is understood by fromisoformat, and sorts correctly as text.