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.
date, datetime and timedelta
Section titled “date, datetime and timedelta”| Type | What it is | Example |
|---|---|---|
date | a calendar day | date(2026, 9, 30) |
datetime | a moment: day and time, with or without a time zone | datetime(2026, 9, 1, 10, 0) |
timedelta | a duration: days, seconds, microseconds | timedelta(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 timedeltaprint((end - start).days) # 1 -- whole days, rounded downprint((start - end).days) # -2 -- down, not toward zeroprint((end - start).total_seconds()) # 169200.0print(start + timedelta(days=30)) # 2026-10-01 10:00:00print(start.date(), start.replace(day=1, hour=0)) # 2026-09-01 2026-09-01 00:00:00print(datetime.combine(date(2026, 9, 30), time())) # 2026-09-30 00:00:00 -- midnight of a dateprint(date(2026, 9, 30) - date(2026, 9, 1)) # 29 days, 0:00:00Subtracting 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()).
Adding months
Section titled “Adding months”timedelta has no months, because months have 28 to 31 days:
import calendarfrom 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), 3total = d.month - 1 + n # months counted from zero: 10 + 3 = 13print(d.year + total // 12, total % 12 + 1) # 2027 2calendar.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:
- Count months from zero:
total = d.month - 1 + n. - The year is
d.year + total // 12, the month istotal % 12 + 1. This works for negativentoo, because//rounds down. - 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.
Renewals count from the original date
Section titled “Renewals count from the original date”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:
| Renewal | From the previous renewal | From the original date |
|---|---|---|
| 0 | 2026-01-31 | 2026-01-31 |
| 1 | 2026-02-28 | 2026-02-28 |
| 2 | 2026-03-28 | 2026-03-31 |
| 3 | 2026-04-28 | 2026-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?”
ISO strings and time zones
Section titled “ISO strings and time zones”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.11b = datetime.fromisoformat("2026-09-03T09:00:00+00:00")print(a, a.tzinfo) # 2026-09-01 10:00:00+00:00 UTCprint(b - a, (b - a).days) # 1 day, 23:00:00 1print((b - a).total_seconds() / 86400) # 1.9583333333333333print(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 versionBefore 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.
Aware and naive datetimes
Section titled “Aware and naive datetimes”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 equalprint(naive.replace(tzinfo=timezone.utc) == aware) # True -- if you know it is UTCnaive < aware # TypeError: can't compare offset-naive and offset-aware datetimesaware - 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 timelate = datetime(2026, 9, 30, 23, 30, tzinfo=timezone.utc)print(late.astimezone(tokyo)) # 2026-10-01 08:30:00+09:00Store 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.)
Practice
Section titled “Practice”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 dExample: 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 calendarfrom 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.
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).daysChecks 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.
Further reading
Section titled “Further reading”- timedelta objects — what a duration stores, and how
.daysandtotal_seconds()work. - datetime.fromisoformat — the accepted formats and the 3.11 change.
- Aware and naive objects — the two kinds of datetime.
- strftime() and strptime() format codes —
%Y,%m,%dand the rest. - calendar.monthrange — the weekday of the first day and the number of days in a month.
- zoneinfo — IANA time zones such as
Europe/Berlin, with daylight saving time.
Related topics
Section titled “Related topics”- Intervals — half-open periods, overlaps and merging.
- Time windows — “the last N seconds” with a
deque. - Filters and dates — half-open date ranges and months in SQL.
- Calendars and active periods — every day, even empty, and “active at a moment”.
- Events and time — renewal dates from ISO durations as a full task.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.