Skip to content

Dates and durations

Subscriptions renew every month, refunds come days after a purchase, and webhooks carry ISO timestamps. So a typical Python task has a date in it: add a month, count the days between two events, group by month. The standard library covers all of it. The traps are a month that is not 30 days, a renewal date that drifts, and two kinds of datetime that cannot be compared.

TypeWhat it isExample
datea calendar daydate(2026, 9, 30)
datetimea moment: day and time, with or without a time zonedatetime(2026, 9, 1, 10, 0)
timedeltaa duration: days, seconds, microsecondstimedelta(days=30)
from datetime import date, datetime, time, timedelta
start = datetime(2026, 9, 1, 10, 0)
end = datetime(2026, 9, 3, 9, 0)
print(end - start) # 1 day, 23:00:00 -- a timedelta
print((end - start).days) # 1 -- whole days, rounded down
print((start - end).days) # -2 -- down, not toward zero
print((end - start).total_seconds()) # 169200.0
print(start + timedelta(days=30)) # 2026-10-01 10:00:00
print(start.date(), start.replace(day=1, hour=0)) # 2026-09-01 2026-09-01 00:00:00
print(datetime.combine(date(2026, 9, 30), time())) # 2026-09-30 00:00:00 -- midnight of a date
print(date(2026, 9, 30) - date(2026, 9, 1)) # 29 days, 0:00:00

Subtracting two datetimes gives a timedelta. Its .days is the number of whole days, rounded down, so 47 hours is 1 day, and minus 47 hours is −2 days. When the task wants hours or a fraction of a day, use total_seconds().

Do not mix date and datetime either: date(2026, 9, 1) < datetime(2026, 9, 1, 10) raises TypeError: '<' not supported between instances of 'datetime.date' and 'datetime.datetime'. Convert one side first, with .date() or datetime.combine(d, time()).

timedelta has no months, because months have 28 to 31 days:

import calendar
from datetime import date, timedelta
print(date(2026, 1, 31) + timedelta(days=30)) # 2026-03-02 -- not "one month later"
print(calendar.monthrange(2026, 2)) # (calendar.SUNDAY, 28)
print(calendar.monthrange(2028, 2)) # (calendar.TUESDAY, 29) -- a leap year
d, n = date(2026, 11, 15), 3
total = d.month - 1 + n # months counted from zero: 10 + 3 = 13
print(d.year + total // 12, total % 12 + 1) # 2027 2

calendar.monthrange(year, month) returns two values: the weekday of the first day and the number of days in the month. You need the second one, [1]. (Since Python 3.12 the weekday prints as calendar.SUNDAY; it is still the number 6.)

So adding n months takes three steps:

  1. Count months from zero: total = d.month - 1 + n.
  2. The year is d.year + total // 12, the month is total % 12 + 1. This works for negative n too, because // rounds down.
  3. Clamp the day to the length of the target month: min(d.day, calendar.monthrange(year, month)[1]). 31 January plus one month is 28 February, or 29 February in a leap year.

A monthly subscription that starts on 31 January renews on the last day of each shorter month. If each renewal is computed from the previous one, the day drifts to the 28th and never comes back:

RenewalFrom the previous renewalFrom the original date
02026-01-312026-01-31
12026-02-282026-02-28
22026-03-282026-03-31
32026-04-282026-04-30

The right column is add_months(start, k) for k = 0, 1, 2, 3. Which rule the billing uses is a question for the interviewer: “Do renewals count from the original date or from the last renewal?”

APIs and webhooks send times as ISO 8601 strings, often with Z for UTC:

from datetime import datetime, timezone
a = datetime.fromisoformat("2026-09-01T10:00:00Z") # "Z" is accepted since Python 3.11
b = datetime.fromisoformat("2026-09-03T09:00:00+00:00")
print(a, a.tzinfo) # 2026-09-01 10:00:00+00:00 UTC
print(b - a, (b - a).days) # 1 day, 23:00:00 1
print((b - a).total_seconds() / 86400) # 1.9583333333333333
print(a.isoformat(), a.strftime("%Y-%m")) # 2026-09-01T10:00:00+00:00 2026-09
s = "2026-09-01T10:00:00Z"
print(datetime.fromisoformat(s.replace("Z", "+00:00")) == a) # True -- works on any version

Before Python 3.11, fromisoformat did not accept Z. The .replace("Z", "+00:00") form works on every version, so it is safe when you do not know which Python the editor runs. ISO date strings in one format, such as '2026-09-01', also sort and compare correctly as plain text. Strings with different offsets do not, so parse them before you compare.

A datetime with tzinfo is aware: it is a precise moment. A datetime without it is naive: it means “10:00 somewhere”. Python refuses to mix them:

aware = datetime(2026, 9, 1, 10, tzinfo=timezone.utc)
naive = datetime(2026, 9, 1, 10)
print(aware == naive) # False -- no error, just never equal
print(naive.replace(tzinfo=timezone.utc) == aware) # True -- if you know it is UTC
naive < aware # TypeError: can't compare offset-naive and offset-aware datetimes
aware - naive # TypeError: can't subtract offset-naive and offset-aware datetimes

< and - fail loudly, but == quietly returns False, so a lookup by time can miss without an error. Make every value aware at the edge of your code: parse with an offset, or attach UTC with replace(tzinfo=timezone.utc) when you know the source is UTC. For “now”, use datetime.now(timezone.utc). datetime.utcnow() returns a naive value and is deprecated since Python 3.12.

The local day can differ from the UTC day. 23:30 UTC on 30 September is already 1 October in Tokyo:

from datetime import timedelta
tokyo = timezone(timedelta(hours=9)) # a fixed offset: Tokyo has no daylight saving time
late = datetime(2026, 9, 30, 23, 30, tzinfo=timezone.utc)
print(late.astimezone(tokyo)) # 2026-10-01 08:30:00+09:00

Store and compute in UTC. Convert to a local zone only to show a time or to group by the customer’s local day, and only when the task asks for it. For zones with daylight saving time, use zoneinfo.ZoneInfo("Europe/Berlin") instead of a fixed offset. (In the browser editor on this site, zoneinfo has no time zone data, so try it in a local Python.)

PythonWrite a functioncore

Add n months to a date (n may be negative); if the day does not exist in the target month, use the last day (Jan 31 + 1 month = Feb 28).

Data and an example

The checks run after your code and can use these:

from datetime import date as d

Example: add_months(d(2026, 1, 31), 1) → d(2026, 2, 28)

6 checks. Your own print() output is shown too.

from datetime import date


def add_months(d, n):
    ...
Show answer

Reference

import calendar
from datetime import date
def add_months(d, n):
total = d.month - 1 + n
year, month = d.year + total // 12, total % 12 + 1
day = min(d.day, calendar.monthrange(year, month)[1])
return date(year, month, day)

Checks and the expected values

  • add_months(d(2026, 1, 31), 1) → datetime.date(2026, 2, 28)
  • add_months(d(2026, 11, 15), 3) → datetime.date(2027, 2, 15)
  • add_months(d(2028, 1, 31), 1) → datetime.date(2028, 2, 29)
  • add_months(d(2026, 3, 31), 12) → datetime.date(2027, 3, 31)
  • add_months(d(2026, 11, 30), 1) → datetime.date(2026, 12, 30)
  • add_months(d(2026, 1, 15), -13) → datetime.date(2024, 12, 15)

timedelta has no months. Compute the year and the month with // and % from a zero-based month, and clamp the day to calendar.monthrange(year, month)[1]. The same code works for a negative n, because // rounds down. Renewals are computed from the original date, not from the previous renewal, or the 31st drifts to the 28th for good.

PythonWrite a function

Given purchase and refund times as ISO strings like '2026-09-01T10:00:00Z', return the delay in whole days (rounded down).

Data and an example

Example: refund_delay_days('2026-09-01T10:00:00Z', '2026-09-03T09:00:00Z') → 1

3 checks. Your own print() output is shown too.

from datetime import datetime


def refund_delay_days(purchased_at, refunded_at):
    ...
Show answer

Reference

from datetime import datetime
def refund_delay_days(purchased_at, refunded_at):
a = datetime.fromisoformat(purchased_at) # Python 3.11+ reads the Z suffix as UTC
b = datetime.fromisoformat(refunded_at)
return (b - a).days

Checks and the expected values

  • refund_delay_days('2026-09-01T10:00:00Z', '2026-09-03T09:00:00Z') → 1
  • refund_delay_days('2026-09-01T10:00:00Z', '2026-09-12T10:00:00Z') → 11
  • refund_delay_days('2026-09-30T23:00:00Z', '2026-10-01T01:00:00Z') → 0

datetime.fromisoformat parses ISO 8601, and since Python 3.11 it reads the Z suffix as UTC, so the plain call is enough. On an older Python, replace the suffix first: s.replace("Z", "+00:00"). The difference of two datetimes is a timedelta, and .days gives whole days rounded down: two hours is 0 days, as in the third check. total_seconds() // 86400 gives the same number as a float, 1.0, and the checks expect an int. Never mix aware and naive datetimes: subtracting them raises TypeError.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.