Python Dates
Python has no separate date type built into the language, but the standard library's datetime module covers almost everything: calendar dates, clock times, combined timestamps, durations, formatting and parsing.
| Class | Represents | Example |
|---|---|---|
date |
a calendar day | 2025-03-14 |
datetime |
a date plus a time of day | 2025-03-14 09:30:00 |
timedelta |
a duration | 3 days, 4:00:00 |
timezone |
a fixed UTC offset | UTC+07:00 |
Note: Real programs often start with
datetime.now()ordate.today(). Those return the current moment, so their output changes every run. To keep the examples on this page reproducible, they use fixed dates instead — swap indatetime.now()in your own code.
Creating dates and datetimes
from datetime import date, datetime
launch = date(2025, 3, 14)
print(launch)
print(launch.year, launch.month, launch.day)
print(launch.weekday()) # Monday is 0, Sunday is 6
print(launch.isoweekday()) # Monday is 1, Sunday is 7
meeting = datetime(2025, 3, 14, 9, 30)
print(meeting)
print(meeting.hour, meeting.minute)
print(meeting.date())2025-03-14
2025 3 14
4
5
2025-03-14 09:30:00
9 30
2025-03-14
The month and day are checked: date(2025, 2, 30) raises ValueError: day is out of range for month.
Formatting with strftime()
strftime ("string format time") turns a date into text according to a pattern of % codes:
| Code | Meaning | Example |
|---|---|---|
%Y |
4-digit year | 2025 |
%m |
month 01–12 | 03 |
%d |
day 01–31 | 14 |
%H / %I |
hour 00–23 / 01–12 | 09 |
%M |
minute | 30 |
%S |
second | 00 |
%p |
AM/PM | AM |
%A / %a |
weekday name / short | Friday / Fri |
%B / %b |
month name / short | March / Mar |
%j |
day of the year | 073 |
from datetime import datetime
dt = datetime(2025, 3, 14, 9, 5, 7)
print(dt.strftime("%d/%m/%Y"))
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
print(dt.strftime("%I:%M %p"))
print(dt.strftime("%A, %d %B %Y"))
print(dt.strftime("Day %j of the year"))
print(f"{dt:%b %d}") # f-strings accept the same codes
print(dt.isoformat())14/03/2025
2025-03-14 09:05:07
09:05 AM
Friday, 14 March 2025
Day 073 of the year
Mar 14
2025-03-14T09:05:07
Tip: Month and weekday names come from the system locale. On most systems they're English, as shown.
Parsing text with strptime()
strptime ("string parse time") does the reverse: it reads text in a known format and returns a datetime:
from datetime import datetime, date
dt = datetime.strptime("21/07/2024 18:45", "%d/%m/%Y %H:%M")
print(dt)
print(repr(dt))
d = date.fromisoformat("2024-12-31")
print(d, type(d).__name__)
try:
datetime.strptime("14 March", "%Y-%m-%d")
except ValueError:
print("ValueError: text does not match the format")2024-07-21 18:45:00
datetime.datetime(2024, 7, 21, 18, 45)
2024-12-31 date
ValueError: text does not match the format
Date arithmetic with timedelta
Subtracting two dates gives a timedelta; adding a timedelta to a date moves it:
from datetime import date, datetime, timedelta
start = date(2025, 1, 28)
print(start + timedelta(days=7))
print(start - timedelta(weeks=2))
deadline = date(2025, 6, 30)
remaining = deadline - start
print(remaining)
print(remaining.days, "days")
checkin = datetime(2025, 5, 1, 14, 0)
checkout = datetime(2025, 5, 4, 11, 30)
stay = checkout - checkin
print(stay)
print(stay.total_seconds() / 3600, "hours")2025-02-04
2025-01-14
153 days, 0:00:00
153 days
2 days, 21:30:00
69.5 hours
timedelta handles month lengths and leap years for you — date(2024, 2, 28) + timedelta(days=1) is 29 February.
Comparing and sorting dates
Dates compare chronologically, so <, max() and sorted() all just work:
from datetime import date
birthdays = {
"Lan": date(1995, 8, 2),
"Quoc": date(1990, 11, 23),
"Hien": date(1998, 1, 15),
}
oldest = min(birthdays, key=birthdays.get)
print("Oldest:", oldest)
for name, d in sorted(birthdays.items(), key=lambda kv: kv[1]):
print(f"{name:<5} {d:%d %b %Y}")
today = date(2025, 3, 14) # pretend "today"
age = today.year - 1995 - ((today.month, today.day) < (8, 2))
print("Lan is", age)Oldest: Quoc
Quoc 23 Nov 1990
Lan 02 Aug 1995
Hien 15 Jan 1998
Lan is 29
Time zones
A datetime without time-zone information is naive. Attach a timezone to make it aware, and convert between zones with astimezone():
from datetime import datetime, timezone, timedelta
vietnam = timezone(timedelta(hours=7))
call = datetime(2025, 3, 14, 20, 0, tzinfo=vietnam)
print(call)
print(call.astimezone(timezone.utc))2025-03-14 20:00:00+07:00
2025-03-14 13:00:00+00:00
For named zones with daylight-saving rules (like "Europe/Paris"), use the zoneinfo module (Python 3.9+).
Test yourself
What does subtracting two date objects return?
- An int number of days
- A timedelta
- A new date
- A string
Which method turns a string like "25/12/2024" into a datetime?
- strftime()
- strptime()
- isoformat()
- parse()
Which format code produces a 4-digit year?
- %y
- %Y
- %D
- %yyyy