Automate everyday tasks with Python · Lesson 8 of 14
Dates and times
Work with dates in scripts: build them with datetime, add days with timedelta, format and parse them with strftime and strptime.
Automation scripts are full of dates: name a report after the day, delete backups older than 30 days, find out when an invoice is due. The datetime module has a date type (a day), a datetime type (a day and a time) and timedelta (a length of time). Code on this page uses fixed dates so the output is always the same; on your own computer you would use date.today() or datetime.now(), shown at the end.
Making dates
from datetime import date, datetime
d = date(2026, 3, 15)
print(d)
print(d.year, d.month, d.day)
print(d.weekday()) # Monday is 0, Sunday is 6
print(d.isoformat())
meeting = datetime(2026, 3, 15, 14, 30)
print(meeting)
print(meeting.date(), meeting.hour, meeting.minute)2026-03-15 2026 3 15 6 2026-03-15 2026-03-15 14:30:00 2026-03-15 14 30
Adding and subtracting: timedelta
Add a timedelta to a date to move forward or back. Subtracting two dates gives a timedelta, whose .days is the number of days between them.
from datetime import date, timedelta
invoice = date(2026, 1, 20)
due = invoice + timedelta(days=30)
print("due:", due)
today = date(2026, 3, 1)
late = today - due
print("days late:", late.days)
print("one week ago:", today - timedelta(weeks=1))
print(date(2026, 12, 25) - today)due: 2026-02-19 days late: 10 one week ago: 2026-02-22 299 days, 0:00:00
Formatting dates: strftime
strftime() (string format time) turns a date into text using codes: %Y year, %m month, %d day, %H:%M hours and minutes, %A weekday name and %B month name. The same codes work inside f-strings after a colon. Tip: put dates in file names year first (YYYY-MM-DD), so alphabetical order is also date order.
from datetime import datetime
t = datetime(2026, 3, 15, 9, 5)
print(t.strftime("%d/%m/%Y"))
print(t.strftime("%A %d %B %Y, %H:%M"))
print(f"report_{t:%Y-%m-%d}.csv")
print(f"backup_{t:%Y%m%d_%H%M}.zip")15/03/2026 Sunday 15 March 2026, 09:05 report_2026-03-15.csv backup_20260315_0905.zip
Reading dates from text: strptime
datetime.strptime() (string parse time) does the reverse: it reads a date from text using the same codes. The format must match the text exactly, otherwise you get a ValueError. For year-first text, date.fromisoformat() is the shortcut.
from datetime import date, datetime
d = datetime.strptime("15.03.2026", "%d.%m.%Y").date()
print(d)
print(date.fromisoformat("2026-07-01"))
for text in ["03/15/2026", "15/03/2026"]:
try:
print(datetime.strptime(text, "%d/%m/%Y").date())
except ValueError:
print(f"{text} does not match day/month/year")2026-03-15 2026-07-01 03/15/2026 does not match day/month/year 2026-03-15
A clean-up script often keeps files from the last N days. If the file names contain the date, the script can decide without looking at anything else.
from datetime import date, timedelta
names = ["backup_2026-02-01.zip", "backup_2026-02-20.zip", "backup_2026-03-10.zip", "backup_2026-03-14.zip"]
today = date(2026, 3, 15)
limit = today - timedelta(days=30)
for name in names:
day = date.fromisoformat(name[7:17])
status = "delete" if day < limit else "keep"
print(f"{name} {status}")backup_2026-02-01.zip delete backup_2026-02-20.zip keep backup_2026-03-10.zip keep backup_2026-03-14.zip keep
# A time-zone offset: a city two hours ahead of UTC, converted to UTC
from datetime import datetime, timedelta, timezone
athens = timezone(timedelta(hours=2))
t = datetime(2026, 3, 15, 9, 0, tzinfo=athens)
print(t.isoformat())
print(t.astimezone(timezone.utc).isoformat())2026-03-15T09:00:00+02:00 2026-03-15T07:00:00+00:00
from datetime import date, datetime
print(date.today()) # today's date on your computer
print(datetime.now().strftime("%H:%M")) # the time right nowThese change every time you run them, so the course never prints them.
✎ Exercise
Each invoice in invoices has a date. Invoices are due 14 days later. Taking 2026-04-10 as today, print the invoice number, its due date and NOT DUE YET or OVERDUE, separated by spaces (overdue means the due date is before today).
Hint: date.fromisoformat(text) reads the date; add timedelta(days=14) and compare with today using <.
from datetime import date, timedelta
invoices = {"A-101": "2026-03-20", "A-102": "2026-03-30", "A-103": "2026-04-02"}
today = date(2026, 4, 10)
# your code here
Expected output:
A-101 2026-04-03 OVERDUE A-102 2026-04-13 NOT DUE YET A-103 2026-04-16 NOT DUE YET
Show a solution
from datetime import date, timedelta
invoices = {"A-101": "2026-03-20", "A-102": "2026-03-30", "A-103": "2026-04-02"}
today = date(2026, 4, 10)
for number, text in invoices.items():
due = date.fromisoformat(text) + timedelta(days=14)
status = "OVERDUE" if due < today else "NOT DUE YET"
print(number, due, status)A-101 2026-04-03 OVERDUE A-102 2026-04-13 NOT DUE YET A-103 2026-04-16 NOT DUE YET
Check yourself
1. What does date(2026, 3, 1) - date(2026, 2, 1) give?
Subtracting dates gives a timedelta; its .days is 28.
2. Which format reads the text "2026-03-15 08:30"?
The codes and the separators must match the text exactly.
3. Why are YYYY-MM-DD dates good in file names?
With the year first, sorting names as text sorts them by date.