Python Tutorial · Working with Data · Lesson 32 of 42

Python Dates and Times

Create, format, parse and do arithmetic with dates using datetime.

The datetime module

Example 1Try it yourself
from datetime import date, datetime

d = date(2026, 3, 15)
print(d, d.year, d.month, d.day)
print(d.strftime("%A"))
moment = datetime(2026, 3, 15, 9, 30)
print(moment)

Output

2026-03-15 2026 3 15
Sunday
2026-03-15 09:30:00

datetime.now() returns the current date and time; its output changes every run, so the examples here use fixed dates.

Formatting and parsing

strftime() formats a date as text; strptime() parses text into a date. ISO 8601 (2026-03-15T09:30:00) is the safest format for APIs.

Example 2Try it yourself
from datetime import datetime

moment = datetime(2026, 3, 15, 9, 30)
print(moment.strftime("%d %B %Y, %H:%M"))
print(moment.isoformat())
parsed = datetime.strptime("15/03/2026", "%d/%m/%Y")
print(parsed.date())
print(datetime.fromisoformat("2026-03-15T09:30:00"))

Output

15 March 2026, 09:30
2026-03-15T09:30:00
2026-03-15
2026-03-15 09:30:00

Date arithmetic

Subtracting dates gives a timedelta; adding a timedelta moves a date.

Example 3Try it yourself
from datetime import date, timedelta

start = date(2026, 3, 15)
deadline = start + timedelta(days=30)
print(deadline)
print((date(2026, 12, 25) - start).days, "days until Christmas")

Output

2026-04-14
285 days until Christmas

Time zones

Store times in UTC and convert for display. Use zoneinfo (standard library since 3.9) for named zones like Europe/London.

Test yourself

Which method turns a string into a datetime?

  1. strftime()
  2. strptime()
  3. parse()
  4. fromstring()
Show answer

Answer: strptime()