Python Dates and Time
The datetime module lets you create, format, compare and calculate dates and times.
The Main Classes
Everything lives in the built-in datetime module. You do not need to install anything.
| Class | Holds | Example |
|---|---|---|
date | Year, month, day | 2026-10-15 |
time | Hour, minute, second | 14:30:00 |
datetime | Date and time together | 2026-10-15 14:30:00 |
timedelta | A length of time | 3 days, 2 hours |
Today and Now
Example
from datetime import date, datetime
print(date.today())
print(datetime.now())2026-10-16 2026-10-16 11:03:35.438075
Your output will show the date and time of your own computer, so it will be different.
Creating a Date
Pass the year, month and day as numbers. Then read each part as an attribute.
Example
from datetime import date, datetime
independence = date(1947, 8, 14)
print(independence)
print(independence.year, independence.month, independence.day)
print(independence.weekday())
print(independence.isoformat())
class_start = datetime(2026, 11, 2, 9, 30)
print(class_start)
print(class_start.hour, class_start.minute)1947-08-14 1947 8 14 3 1947-08-14 2026-11-02 09:30:00 9 30
weekday() counts Monday as 0, so 3 means Thursday.
Formatting With strftime()
strftime() turns a date into text in the format you choose, using codes that start with %.
| Code | Meaning | Example |
|---|---|---|
%d | Day, two digits | 05 |
%m | Month, two digits | 08 |
%B | Full month name | August |
%b | Short month name | Aug |
%Y | Year, four digits | 2026 |
%A | Full day name | Thursday |
%H | Hour, 24-hour clock | 17 |
%I | Hour, 12-hour clock | 05 |
%M | Minutes | 45 |
%p | AM or PM | PM |
Example
from datetime import datetime
exam = datetime(2026, 12, 3, 17, 45)
print(exam.strftime("%d-%m-%Y"))
print(exam.strftime("%A, %d %B %Y"))
print(exam.strftime("%I:%M %p"))
print(f"Exam on {exam:%d %b} at {exam:%H:%M}")03-12-2026 Thursday, 03 December 2026 05:45 PM Exam on 03 Dec at 17:45
The last line shows that f-strings understand the same codes after a colon.
Reading Dates From Text
strptime() does the opposite: it turns text into a datetime. You must tell it the format of the text.
Example
from datetime import datetime, date
typed = "25/12/2026"
d = datetime.strptime(typed, "%d/%m/%Y")
print(d)
print(d.strftime("%A"))
print(date.fromisoformat("2026-03-23"))2026-12-25 00:00:00 Friday 2026-03-23
If the text does not match the format, Python raises a ValueError. Wrap it in try...except when the text comes from a user.
Date Maths With timedelta
Subtracting two dates gives a timedelta. Adding a timedelta to a date moves it forward.
Example
from datetime import date, timedelta
admission = date(2026, 10, 15)
course_length = timedelta(weeks=12)
print("Course ends:", admission + course_length)
fee_due = admission + timedelta(days=30)
print("Fee due:", fee_due)
eid = date(2027, 3, 10)
left = eid - admission
print("Days until Eid:", left.days)
birthday = date(2004, 6, 1)
today = date(2026, 10, 15)
age = today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day))
print("Age:", age)Course ends: 2027-01-07 Fee due: 2026-11-14 Days until Eid: 146 Age: 22
The age line subtracts 1 when this year's birthday has not come yet. True counts as 1 and False as 0.
Comparing Dates
Dates compare just like numbers.
Example
from datetime import date
deadline = date(2026, 10, 20)
submitted = date(2026, 10, 18)
print(submitted <= deadline)
dates = [date(2026, 5, 1), date(2025, 12, 31), date(2026, 1, 15)]
print(min(dates), max(dates))
print(sorted(dates))True 2025-12-31 2026-05-01 [datetime.date(2025, 12, 31), datetime.date(2026, 1, 15), datetime.date(2026, 5, 1)]
Time Zones
Use zoneinfo (Python 3.9+) to work with real time zones. Pakistan is in Asia/Karachi.
Example
from datetime import datetime
from zoneinfo import ZoneInfo
meeting = datetime(2026, 10, 15, 20, 0, tzinfo=ZoneInfo("Asia/Karachi"))
print(meeting)
print(meeting.astimezone(ZoneInfo("Europe/London")))
print(meeting.astimezone(ZoneInfo("America/New_York")).strftime("%d %b %I:%M %p"))2026-10-15 20:00:00+05:00 2026-10-15 16:00:00+01:00 15 Oct 11:00 AM
This is very useful for freelancers who talk to clients in other countries.
On Windows, zoneinfo may need the extra package tzdata. Install it with pip install tzdata if you get a "No time zone found" error.
The time Module
The separate time module is handy for pauses and measuring how long code takes.
Example
import time
start = time.perf_counter()
time.sleep(1)
print(f"Waited {time.perf_counter() - start:.1f} seconds")Waited 1.0 seconds
Exercise
Exercise
Which method turns the text "14/08/2026" into a datetime object?
