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.

About 16 minutes · code runs in your browser, nothing to install

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

Pythoneditable
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)
Output
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.

Pythoneditable
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)
Output
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.

Pythoneditable
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")
Output
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.

Pythoneditable
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")
Output
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.

Pythoneditable
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}")
Output
backup_2026-02-01.zip  delete
backup_2026-02-20.zip  keep
backup_2026-03-10.zip  keep
backup_2026-03-14.zip  keep
Pythoneditable
# 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())
Output
2026-03-15T09:00:00+02:00
2026-03-15T07:00:00+00:00
On your own computer
from datetime import date, datetime

print(date.today())                        # today's date on your computer
print(datetime.now().strftime("%H:%M"))    # the time right now

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

Your codewrite your answer, then Run
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
Solutioneditable
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)
Output
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?

2. Which format reads the text "2026-03-15 08:30"?

3. Why are YYYY-MM-DD dates good in file names?

Spotted a mistake on this page? Tell us