Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Dates and Times

Dates and times appear in almost every real program: birthdays, deadlines, timestamps in logs, opening hours. Python's datetime module has types for dates, times and combinations of both, and it knows about months of different lengths and leap years, so you never have to count days by hand.

Creating dates and times

from datetime import date, datetime

independence = date(1947, 8, 15)
print(independence)
print(independence.year, independence.month, independence.day)
meeting = datetime(2026, 10, 21, 14, 30)
print(meeting)
print(independence.weekday(), independence.strftime("%A"))
Output
1947-08-15
1947 8 15
2026-10-21 14:30:00
4 Friday

date holds a day, datetime a day and a time. weekday() numbers the days from Monday = 0, so 4 is a Friday. date.today() and datetime.now() give the current date and time when your program runs.

Formatting and reading dates

strftime turns a date into text in the format you describe with codes such as %d (day), %m (month number), %B (month name), %Y (year), %H and %M (hours and minutes). strptime does the opposite, reading a date from text:

from datetime import datetime

d = datetime(2026, 10, 21, 9, 5)
print(d.strftime("%d/%m/%Y"))
print(d.strftime("%A, %d %B %Y at %H:%M"))
parsed = datetime.strptime("25-12-2026", "%d-%m-%Y")
print(parsed.date(), parsed.strftime("%a %b %d"))
Output
21/10/2026
Wednesday, 21 October 2026 at 09:05
2026-12-25 Fri Dec 25

Calculating with dates

Subtracting two dates gives a timedelta, a length of time. Adding a timedelta to a date moves it forward:

from datetime import date, timedelta

start = date(2026, 10, 21)
exam = date(2026, 12, 15)
print((exam - start).days, "days to go")
print(start + timedelta(days=100))
print(start + timedelta(weeks=2))
born = date(2005, 3, 10)
age = start.year - born.year - ((start.month, start.day) < (born.month, born.day))
print("Age:", age)
Output
55 days to go
2027-01-29
2026-11-04
Age: 21

The age calculation subtracts one when the birthday has not yet come this year: comparing the (month, day) tuples gives True, which counts as 1.

Time zones

A plain datetime does not know its time zone. For times in several places, the zoneinfo module attaches a zone, such as ZoneInfo("Asia/Kolkata"), and converts between zones correctly.

Practice exercises

  1. Print the day of the week you were born on.
  2. Print how many days are left until the next New Year.
  3. Read a date typed as dd/mm/yyyy with strptime and print it as 21 October 2026.
  4. Print the dates of the next four Mondays after a given date.