Skip to content

Intermediate · Errors, modules and the standard library · topic 24 of 50 · 20 min

Dates and times with datetime

Explanation

The datetime module handles dates and times: date for a calendar day, datetime for a day plus a clock time, and timedelta for a gap such as 30 days. strftime turns a date into text like "15-08-2024", and strptime reads such text back into a date. Subtracting two dates tells you how many days lie between them.

Three useful types

TypeHoldsExample
datea calendar daydate(2024, 8, 15)
datetimea day and a clock timedatetime(2024, 8, 15, 9, 30)
timedeltaa length of time (a gap)timedelta(days=30)
python
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 6
Shows 2024-08-15, then 2024 8 15, then 3 (a Thursday).

date.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.

Think of it like this: Think of a wall calendar. A date is one page. A timedelta is the number of pages you flip: flip 30 pages forward from 15 August and you land on 14 September. Subtracting two dates counts the pages between them.

Adding and subtracting

python
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")
date + timedelta gives a new date; date - date gives a timedelta.

Turning dates into text: strftime

CodeMeansFor 5 Sep 2024
%dday, two digits05
%mmonth, two digits09
%Yyear, four digits2024
%B / %bmonth name, full / shortSeptember / Sep
%Aweekday nameThursday
%H:%Mhour (00-23) and minute14:05
python
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"))
Shows 05-09-2024, then 05 September 2024, then Thursday.
Tip: Remember the names this way: strftime is "string from time" (date to text), strptime is "string parse time" (text to date). India writes day-month-year; the ISO style 2024-09-05 (year first) sorts correctly as plain text, so it is best for file names.

Reading text into dates: strptime

python
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)
strptime returns a datetime; .date() keeps only the day.
Careful: The format must match the text exactly: slashes, dashes and order. Also, 03-04-2025 means 3 April in India but March 4 in the USA. Never guess; always say which format you are reading.

Calculating age correctly

python
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)))
Shows 23, then 24: the birthday is on 2 October.
Careful: Do not calculate age as days // 365. Leap years add an extra day every four years, so that shortcut is wrong around birthdays.

Watch the lesson

Dates and times with datetime · 1/7

Dates and times

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.

python
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"))
Booking opens on 13-01-2025, Monday

Practice (0/3 done)

Task 1 · Code · Python

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.

Task 2 · Code · Python

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".

Task 3 · Code · Python

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

Question 1

1.What is date(2024, 1, 31) + timedelta(days=1)?

Question 2

2.What does date(2025, 1, 26).strftime("%d-%m-%Y") give?

Question 3

3.Which code gives the four-digit year?

Question 4

4.What happens with datetime.strptime("31/12/2024", "%d-%m-%Y")?

Question 5

5.Why do tests use fixed dates instead of date.today()?

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.

← Previous: Modules and imports