Intermediate · Errors, modules and the standard library · topic 24 of 50 · 20 min
Dates and times with datetime
Explanation
Three useful types
| Type | Holds | Example |
|---|---|---|
| date | a calendar day | date(2024, 8, 15) |
| datetime | a day and a clock time | datetime(2024, 8, 15, 9, 30) |
| timedelta | a length of time (a gap) | timedelta(days=30) |
from datetime import date
d = date(2024, 8, 15)
print(d)
print(d.year, d.month, d.day)
print(d.weekday()) # Monday is 0, Sunday is 6date.today() gives the current date. It is handy in real apps, but its answer changes every day. In examples and tests we always use fixed dates like date(2024, 8, 15), so the result is the same whenever the code runs.
Adding and subtracting
from datetime import date, timedelta
bill_date = date(2024, 8, 15)
due = bill_date + timedelta(days=30)
print(due)
exam_day = date(2024, 11, 1)
gap = exam_day - bill_date
print(gap.days, "days to the exam")Turning dates into text: strftime
| Code | Means | For 5 Sep 2024 |
|---|---|---|
| %d | day, two digits | 05 |
| %m | month, two digits | 09 |
| %Y | year, four digits | 2024 |
| %B / %b | month name, full / short | September / Sep |
| %A | weekday name | Thursday |
| %H:%M | hour (00-23) and minute | 14:05 |
from datetime import date
d = date(2024, 9, 5)
print(d.strftime("%d-%m-%Y"))
print(d.strftime("%d %B %Y"))
print(d.strftime("%A"))Reading text into dates: strptime
from datetime import datetime
d = datetime.strptime("26-01-2025", "%d-%m-%Y").date()
print(d, d.strftime("%A"))
try:
datetime.strptime("26/01/2025", "%d-%m-%Y")
except ValueError as e:
print("Wrong format:", e)Calculating age correctly
from datetime import date
def age_on(birth, on):
years = on.year - birth.year
if (on.month, on.day) < (birth.month, birth.day):
years -= 1 # birthday not reached yet this year
return years
print(age_on(date(2000, 10, 2), date(2024, 10, 1)))
print(age_on(date(2000, 10, 2), date(2024, 10, 2)))Watch the lesson
Dates and times with datetime · 1/7
Bills, birthdays, train journeys and exams all depend on dates. In this lesson you will learn Python's datetime module.
Prefer a video by a teacher? Find free videos on “python datetime strftime strptime timedelta tutorial” on YouTube ↗
In real life: When does ticket booking open?
Suppose a railway opens booking 60 days before the journey, not counting the journey day itself. Imran plans to travel on 14 March 2025 and wants to know the exact date to set an alarm. One subtraction with timedelta gives the answer, printed the Indian way.
from datetime import date, timedelta
journey = date(2025, 3, 14)
opens = journey - timedelta(days=60)
print("Booking opens on", opens.strftime("%d-%m-%Y, %A"))Practice (0/3 done)
Write days_between(a, b) where a and b are dates as text in the Indian format "dd-mm-yyyy". Return the number of days between them as a positive number. days_between("01-01-2024", "01-03-2024") returns 60.
Write to_indian(iso_text) that turns a date written as "yyyy-mm-dd" into the Indian style "dd-mm-yyyy". to_indian("2024-08-15") returns "15-08-2024".
Write age_on(birth, on) that returns a person's age in whole years on the date on. Both are date objects. Remember to subtract one if the birthday has not come yet that year.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.