Skip to the content.

Dates and times: Python snippets

Part of 30 Seconds of Python. Source: snippets/dates.py. Every example below is run as a test.

utc_now

Current time as an aware UTC datetime (datetime.utcnow() is deprecated).

def utc_now():
    return datetime.now(timezone.utc)
>>> utc_now().tzinfo is timezone.utc
True

parse_iso

Parse an ISO 8601 timestamp; a trailing ā€˜Z’ is accepted on every Python 3.7+.

def parse_iso(text):
    if text.endswith('Z'):
        text = text[:-1] + '+00:00'
    return datetime.fromisoformat(text)
>>> parse_iso('2026-12-01T09:30:00Z')
datetime.datetime(2026, 12, 1, 9, 30, tzinfo=datetime.timezone.utc)

days_between

Whole days from date a to date b (negative if b is earlier).

def days_between(a, b):
    return (b - a).days
>>> days_between(date(2026, 1, 1), date(2026, 12, 1))
334

add_business_days

Add n weekdays (Mon-Fri) to a date. Holidays are not considered.

def add_business_days(start, n):
    step = 1 if n >= 0 else -1
    current, left = start, abs(n)
    while left:
        current += timedelta(days=step)
        if current.weekday() < 5:
            left -= 1
    return current
>>> add_business_days(date(2026, 11, 27), 1)  # Friday -> Monday
datetime.date(2026, 11, 30)

date_range

Dates from start up to and including end.

def date_range(start, end, step_days=1):
    d = start
    while d <= end:
        yield d
        d += timedelta(days=step_days)
>>> [d.day for d in date_range(date(2026, 2, 26), date(2026, 3, 2))]
[26, 27, 28, 1, 2]

is_leap_year

Gregorian leap year rule.

def is_leap_year(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
>>> [is_leap_year(y) for y in (1900, 2000, 2024, 2026)]
[False, True, True, False]

age

Age in whole years on today.

def age(born, today):
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
>>> age(date(2000, 12, 2), date(2026, 12, 1))
25

human_duration

Readable duration like ā€˜1h 2m 3s’.

def human_duration(seconds):
    seconds = int(seconds)
    parts = []
    for unit, size in (('d', 86400), ('h', 3600), ('m', 60), ('s', 1)):
        value, seconds = divmod(seconds, size)
        if value:
            parts.append(f'{value}{unit}')
    return ' '.join(parts) or '0s'
>>> human_duration(3723), human_duration(59), human_duration(90061)
('1h 2m 3s', '59s', '1d 1h 1m 1s')

start_of_week

Monday of the week containing d.

def start_of_week(d):
    return d - timedelta(days=d.weekday())
>>> start_of_week(date(2026, 12, 3))
datetime.date(2026, 11, 30)