Python has a built-in
datetime module that handles dates, times, and durations. It is part of the standard library, so you never need to install anything extra.Creating a date
from datetime import date
today = date.today()
print(today)date objects hold a year, month, and day. You can create one for any specific day by passing three whole numbers: year, month, then day. Months count from 1 (January is 1). Days run from 1 to the last valid day of that month.from datetime import date
birthday = date(2003, 5, 14)
print(birthday.year) # 2003
print(birthday.month) # 5
print(birthday.day) # 14Measuring the gap between two dates
from datetime import date
day_one = date(2024, 1, 1)
day_two = date(2024, 3, 15)
gap = day_two - day_one
print(gap.days) # 74Subtracting two
date objects gives you a timedelta. A timedelta represents a duration of time. You can inspect its .days, .seconds, and .microseconds attributes to see exactly how long the gap is.Adding days with timedelta
from datetime import date, timedelta
start = date(2024, 10, 5)
next_week = start + timedelta(days=7)
print(next_week) # 2024-10-12Formatting with strftime
from datetime import date
d = date(2024, 12, 25)
print(d.strftime('%Y-%m-%d')) # 2024-12-25
print(d.strftime('%d %B %Y')) # 25 December 2024strftime stands for string format time. You pass it a format string made of special codes. %Y is the four-digit year, %m is the month as two digits (01 to 12), %d is the day as two digits (01 to 31), and %B is the month's full name. Use this to turn dates into human-readable text.