Python Tutorial menu

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.

ClassHoldsExample
dateYear, month, day2026-10-15
timeHour, minute, second14:30:00
datetimeDate and time together2026-10-15 14:30:00
timedeltaA length of time3 days, 2 hours

Today and Now

Example

python
from datetime import date, datetime

print(date.today())
print(datetime.now())
Output
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

python
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)
Output
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 %.

CodeMeaningExample
%dDay, two digits05
%mMonth, two digits08
%BFull month nameAugust
%bShort month nameAug
%YYear, four digits2026
%AFull day nameThursday
%HHour, 24-hour clock17
%IHour, 12-hour clock05
%MMinutes45
%pAM or PMPM

Example

python
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}")
Output
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

python
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"))
Output
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

python
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)
Output
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

python
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))
Output
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

python
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"))
Output
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

python
import time

start = time.perf_counter()
time.sleep(1)
print(f"Waited {time.perf_counter() - start:.1f} seconds")
Output
Waited 1.0 seconds

Exercise

Exercise

Which method turns the text "14/08/2026" into a datetime object?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp