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 integers: year, month, then day. Months are 1-indexed (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
today = date(2024, 10, 5)
next_week = today + 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('%B %d, %Y')) # December 25, 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 zero-padded month (01-12), and %d is the zero-padded day (01-31). Use this to turn dates into human-readable text.