Dates and Times · Examples
Core Python

Dates and Times Examples

Short, runnable programs that show python datetime module in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python datetime Module lesson.

1One moment, many formats

The same datetime can be written for a log, an invoice or a file name just by changing the strftime template.

One moment, many formats
from datetime import datetime

order_time = datetime(2025, 11, 3, 9, 7, 45)
print("ISO:     ", order_time.isoformat())
print("Invoice: ", order_time.strftime("%d %b %Y"))
print("Receipt: ", order_time.strftime("%d/%m/%y %I:%M %p"))
print("Log:     ", order_time.strftime("%Y-%m-%d %H:%M:%S"))
print("Filename:", order_time.strftime("backup_%Y%m%d_%H%M.zip"))
print("Weekday: ", order_time.strftime("%A"))
Expected outputISO:      2025-11-03T09:07:45
Invoice:  03 Nov 2025
Receipt:  03/11/25 09:07 AM
Log:      2025-11-03 09:07:45
Filename: backup_20251103_0907.zip
Weekday:  Monday

2Session lengths from log lines

Parse each timestamp with strptime, subtract to get a timedelta, and convert to minutes with total_seconds(). Cara's session crosses midnight and still comes out right.

Session lengths from log lines
from datetime import datetime

log = [
    ("asha", "2025-03-07 09:15", "2025-03-07 10:45"),
    ("ben", "2025-03-07 13:00", "2025-03-07 13:20"),
    ("cara", "2025-03-07 23:30", "2025-03-08 00:10"),
]
fmt = "%Y-%m-%d %H:%M"
total_minutes = 0
for user, start, end in log:
    gap = datetime.strptime(end, fmt) - datetime.strptime(start, fmt)
    minutes = gap.total_seconds() / 60
    total_minutes += minutes
    print(f"{user:<5} {int(minutes):>3} min")
print("Total:", int(total_minutes), "min")
Expected outputasha   90 min
ben    20 min
cara   40 min
Total: 150 min

3Days left in the month

The month-end trick from the lesson, applied to three dates, including a leap-year February and the last day of the year.

Days left in the month
from datetime import date, timedelta

def month_end(value):
    first_of_next = (value.replace(day=28) + timedelta(days=4)).replace(day=1)
    return first_of_next - timedelta(days=1)

for d in [date(2025, 1, 15), date(2024, 2, 10), date(2025, 12, 31)]:
    end = month_end(d)
    print(d, "-> month ends", end, "| days left:", (end - d).days)
Expected output2025-01-15 -> month ends 2025-01-31 | days left: 16
2024-02-10 -> month ends 2024-02-29 | days left: 19
2025-12-31 -> month ends 2025-12-31 | days left: 0

4A deadline countdown

Sort the deadlines by date, then use the sign of the difference to choose a message. The f-string prints the weekday and month straight from the date object.

A deadline countdown
from datetime import date

today = date(2025, 3, 7)
deadlines = {
    "Tax return": date(2025, 4, 15),
    "Passport renewal": date(2025, 3, 20),
    "Library book": date(2025, 3, 5),
}
for name, due in sorted(deadlines.items(), key=lambda item: item[1]):
    days = (due - today).days
    if days < 0:
        status = f"overdue by {-days} days"
    elif days == 0:
        status = "due today"
    else:
        status = f"{days} days left"
    print(f"{name:<17} {due:%a %d %b}  {status}")
Expected outputLibrary book      Wed 05 Mar  overdue by 2 days
Passport renewal  Thu 20 Mar  13 days left
Tax return        Tue 15 Apr  39 days left

5One meeting, three time zones

Aware datetimes can be compared and subtracted even when they use different offsets. astimezone() only changes how the same moment is displayed.

One meeting, three time zones
from datetime import datetime, timedelta, timezone

utc = timezone.utc
india = timezone(timedelta(hours=5, minutes=30))
new_york = timezone(timedelta(hours=-5))

meeting = datetime(2025, 3, 7, 15, 0, tzinfo=utc)
for city, zone in [("UTC", utc), ("India", india), ("New York", new_york)]:
    local = meeting.astimezone(zone)
    print(f"{city:<9} {local:%H:%M on %a %d %b}")

reply = datetime(2025, 3, 7, 21, 30, tzinfo=india)
print("Reply sent", reply - meeting, "after the meeting began")
Expected outputUTC       15:00 on Fri 07 Mar
India     20:30 on Fri 07 Mar
New York  10:00 on Fri 07 Mar
Reply sent 1:00:00 after the meeting began

6Monthly totals from ISO dates

Dates stored as ISO text, as in a CSV file, are easy to read back with fromisoformat(). Formatting each one as %Y-%m gives a key that groups by month and also sorts in order.

Monthly totals from ISO dates
from datetime import date

expenses = [
    ("2025-01-14", 45.50),
    ("2025-01-30", 20.00),
    ("2025-02-03", 12.25),
    ("2025-02-27", 80.00),
    ("2025-03-01", 15.75),
]
totals = {}
for text, amount in expenses:
    key = date.fromisoformat(text).strftime("%Y-%m")
    totals[key] = totals.get(key, 0) + amount

for key, total in sorted(totals.items()):
    month = date.fromisoformat(key + "-01").strftime("%B %Y")
    print(f"{month:<14}{total:>7.2f}")
Expected outputJanuary 2025    65.50
February 2025   92.25
March 2025      15.75

Practise next

Python datetime Module exercises → Back to the lesson

Python Strings examplesPython Modules and Imports examplesPython math and statistics examplesPython CSV Files examples