Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 149 ยท Modules and the Standard Library

Dates and Times

Work with dates and times in Python using datetime, date and timedelta. Do date math, format and parse strings with strftime and strptime, and handle time zones.

Dates look simple until you have to calculate with them. How many days until a deadline? What weekday was March 1st? What time is a 15:00 meeting in Tokyo for someone in Berlin? Python's datetime module answers all of these with a handful of well-designed types.

This lesson covers the four types you'll use most (date, time, datetime and timedelta), date arithmetic, turning dates into text and back, and how to deal with time zones correctly.

The main types

The datetime module (lowercase) contains a class also called datetime, which trips up many beginners. These are the pieces:

Type Holds Example
date year, month, day date(2026, 7, 4)
time hour, minute, second, microsecond time(9, 30)
datetime a date plus a time datetime(2026, 7, 4, 9, 30)
timedelta a duration timedelta(days=3, hours=2)
Python Creating dates and times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All of these objects are immutable. To change one part, call .replace(), which returns a new object: launch.replace(year=2027).

Python checks your values, so date(2026, 2, 30) raises a ValueError explaining that February 2026 has only 28 days. That's a feature: invalid dates never sneak into your program.

Today and now

date.today() returns the current local date, and datetime.now() the current local date and time:

Python
from datetime import date, datetime

print(date.today())        # e.g. 2026-10-14
print(datetime.now())      # e.g. 2026-10-14 09:12:47.105822

Because the output changes every second, most examples in this lesson use fixed dates so you can predict the results. The browser editor's clock follows your device, but its local time zone is usually UTC.

Date arithmetic with timedelta

A timedelta represents a length of time. Add one to a date to move forward; subtract two dates to get the distance between them:

Python Adding and subtracting time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

timedelta stores only days, seconds and microseconds internally. Use .days for whole days and .total_seconds() for an exact figure; the .seconds attribute is only the leftover part after the days, a common source of bugs.

There's no timedelta(months=1). Months have different lengths, so "one month later" is ambiguous (what's one month after January 31?). Decide your rule and code it, for example with .replace(month=...) plus a check, or use the third-party python-dateutil package and its relativedelta.

You can also compare dates with <, > and ==, sort lists of them, and use them as dictionary keys:

Python Comparing and sorting dates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Formatting dates as text

isoformat() gives the international standard format (ISO 8601), the best choice for files, logs and APIs. For human-friendly text, use strftime() ("string format time") with format codes, or put the same codes in an f-string:

Python strftime and f-strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The most useful format codes:

Code Meaning Example
%Y / %y year, 4 or 2 digits 2026 / 26
%m month number, zero-padded 09
%B / %b month name, full / short September / Sep
%d day of month, zero-padded 05
%A / %a weekday name, full / short Saturday / Sat
%H / %I hour, 24-hour / 12-hour 18 / 06
%M / %S minute / second 07 / 30
%p AM or PM PM
%j day of the year 248
%z / %Z UTC offset / zone name +0200 / CEST

Month and weekday names follow the system locale, which is English in most setups. For multilingual sites, a library such as Babel handles translations properly.

Parsing text into dates

Going the other way, strptime() ("string parse time") reads text using the same codes. For ISO-formatted text, fromisoformat() is simpler and faster:

Python Parsing dates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Since Python 3.11, fromisoformat() accepts nearly every ISO 8601 variant, including a Z suffix for UTC. Always wrap parsing of user input in try/except ValueError; people type dates in endless creative ways.

Time zones

A datetime without time zone information is called naive; one with a zone attached is aware. Naive values are fine for things like a birthday or a local alarm. As soon as you compare moments across places, store timestamps, or talk to other systems, use aware values, ideally in UTC.

The built-in timezone class represents a fixed offset from UTC:

Python Aware datetimes with fixed offsets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

astimezone() converts an aware datetime to another zone: same instant, different wall-clock reading. To get the current moment as an aware value, use datetime.now(timezone.utc). Avoid the old datetime.utcnow(); it returns a naive value and is deprecated since Python 3.12.

Real time zones with zoneinfo

Fixed offsets ignore daylight saving time: New York is UTCโˆ’5 in winter but UTCโˆ’4 in summer. For real places, use the zoneinfo module (Python 3.9+), which knows the rules of every IANA zone such as "Europe/Berlin" or "America/Sao_Paulo":

Python
from datetime import datetime
from zoneinfo import ZoneInfo

berlin = ZoneInfo("Europe/Berlin")
call = datetime(2026, 7, 10, 15, 0, tzinfo=berlin)

print(call)                                          # 2026-07-10 15:00:00+02:00
print(call.astimezone(ZoneInfo("Asia/Tokyo")))       # 2026-07-10 22:00:00+09:00
print(call.astimezone(ZoneInfo("America/New_York"))) # 2026-07-10 09:00:00-04:00

winter = datetime(2026, 1, 10, 15, 0, tzinfo=berlin)
print(winter.utcoffset())                            # 1:00:00 (summer was 2:00:00)

Run zoneinfo examples on your computer. zoneinfo reads the operating system's time zone database. On Windows (and in this browser runner) that database may be missing, and ZoneInfo("Europe/Berlin") raises ZoneInfoNotFoundError. The fix is python -m pip install tzdata, the official data package that zoneinfo uses automatically.

A good rule for applications: store and compute in UTC, and convert to the user's zone only when you display a time.

Timestamps

Many systems exchange times as a Unix timestamp: seconds since 1970-01-01 00:00 UTC. Convert in both directions, and pass a zone so the result is aware:

Python Unix timestamps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For measuring how long code takes, use time.perf_counter() rather than datetime; it's a high-resolution clock that never jumps when the system time changes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is date(2026, 3, 1) - date(2026, 2, 1)?

    Subtracting two dates gives a timedelta. Its .days attribute is 28, because February 2026 has 28 days.
  2. 2. Which method turns the text "07/04/2026" into a datetime?

    strptime() parses text with a format. strftime() does the reverse, and fromisoformat() only accepts ISO formats like 2026-07-04.
  3. 3. A duration is 2 days and 3 hours. What does .seconds return?

    .seconds is the remainder after .days. Use .total_seconds() (183600.0) for the full length.
  4. 4. Why should you prefer zoneinfo over a fixed timezone(timedelta(hours=1)) for Paris?

    Paris switches between UTC+1 and UTC+2. ZoneInfo("Europe/Paris") knows the rules; a fixed offset doesn't.

Summary

  • date, time, datetime and timedelta cover calendar days, clock times, moments and durations; all are immutable.
  • Add or subtract a timedelta to move in time; subtracting dates gives a timedelta (use .days or .total_seconds()).
  • strftime() and f-strings (f"{d:%Y-%m-%d}") format dates; strptime() and fromisoformat() parse them.
  • Naive datetimes have no zone; aware ones do. Prefer aware UTC values for storage and comparison.
  • timezone handles fixed offsets; zoneinfo.ZoneInfo handles real places with daylight saving (install tzdata where the system lacks zone data).

Next: collections, where you'll meet Counter, defaultdict, deque and other specialized containers.