Programming languages · Intermediate · 25 min
Store and show dates and times correctly across time zones
By Padding · Updated 18 Nov 2026
Python 3.15.2 · uv 0.13 · Node.js 26.13 · PostgreSQL 18
You will fix a meeting scheduler that books calls an hour off, and end with a small Python time module, a rule set and tests that hold across Lagos, Nairobi and London clock changes.
On this page
A team booked a call for 15:00 London time on 15 July. The organiser in London joined at 15:00. The colleagues in Lagos and Nairobi, whose calendars came from the same app, joined an hour late. Nothing crashed, no test failed, and the bug only appears for half the year.
This kind of bug comes from treating a time as a number with an offset added on. In this tutorial you reproduce it, then fix it one idea at a time with Python's standard zoneinfo module: aware datetimes, UTC instants for storage, zone names for future local times, clock-change gaps and overlaps, "one day" versus 24 hours, and the string formats that carry a time between systems. You see the same ideas in JavaScript's Temporal API and in PostgreSQL's timestamptz, and you finish with a short module and tests that pin the rules down.
Three zones carry the examples. Africa/Lagos (UTC+1) and Africa/Nairobi (UTC+3) have no daylight saving time. Europe/London is UTC+0 in winter and UTC+1 in summer; in 2026 the clocks go forward on 29 March and back on 25 October.
Step 1 · Set up the project and reproduce the bug
Create a demo project and add tzdata, the IANA time zone database packaged for Python. zoneinfo reads the system's database first and falls back to this package, which Windows and some slim Linux images need:
mkdir -p ~/tz-demo
cd ~/tz-demo
uv init --no-package
uv add "tzdata>=2026.6"Now write the scheduler as it was. It stores the booked time without a zone and shows it to each attendee by adding an offset someone measured in January:
cat > buggy.py <<'PY'
from datetime import datetime, timedelta
# Hours ahead of London, written down in January.
HOURS_AHEAD_OF_LONDON = {"Europe/London": 0, "Africa/Lagos": 1, "Africa/Nairobi": 3}
booked = datetime(2026, 7, 15, 15, 0) # meant as 15:00 London time
print("tzinfo:", booked.tzinfo)
for zone, hours in HOURS_AHEAD_OF_LONDON.items():
local = booked + timedelta(hours=hours)
print(f"{zone:15} {local:%d %b %H:%M}")
PY
uv run buggy.py | tee buggy.outCheck it worked
The output starts with tzinfo: None and shows Lagos at 15 Jul 16:00 and Nairobi at 15 Jul 18:00. In July London is on UTC+1, the same as Lagos, so the right answers are 15:00 and 17:00. The datetime has no zone attached (Python calls this a naive datetime), and the offsets are only true in winter.
Step 2 · Store UTC instants with aware datetimes
An aware datetime carries a tzinfo, so Python knows which moment it means. Attach the organiser's zone to the time they typed, convert to UTC for storage, and convert to each attendee's zone only when you show it:
cat > aware.py <<'PY'
from datetime import UTC, datetime
from zoneinfo import ZoneInfo
booked = datetime(2026, 7, 15, 15, 0, tzinfo=ZoneInfo("Europe/London"))
stored = booked.astimezone(UTC)
print("stored:", stored.isoformat())
for name in ("Europe/London", "Africa/Lagos", "Africa/Nairobi"):
local = stored.astimezone(ZoneInfo(name))
print(f"{name:15} {local:%d %b %H:%M} UTC{local:%z}")
try:
print(datetime(2026, 7, 15, 15, 0) < stored)
except TypeError as err:
print("refused:", err)
PY
uv run aware.py | tee aware.outUTC never has clock changes, so an instant stored in UTC sorts, compares and subtracts correctly no matter who reads it. The last lines show that Python refuses to compare a naive datetime with an aware one, which is a useful alarm. For the current moment, use datetime.now(UTC). datetime.utcnow() returns a naive value and has been deprecated since Python 3.12.
Take "now" from your server, not from the user's device. Many phones, including budget Android handsets that have been off or out of credit for a while, run with a wrong clock or a manually set zone.
Check it worked
The output shows stored: 2026-07-15T14:00:00+00:00, Lagos at 15 Jul 15:00 UTC+0100, Nairobi at 15 Jul 17:00 UTC+0300, and a line starting refused: can't compare offset-naive and offset-aware datetimes.
Step 3 · Keep the zone name for future local times
A UTC instant is right for something that has already happened, or a one-off event booked close to now. A repeating meeting is different. "Every Monday at 09:00 London time" is a promise about the wall clock in London, and its UTC time moves when the clocks change. If you store only the offset in force on the day of booking (+01:00), every meeting after 25 October lands an hour early.
Compare the zone name with a fixed offset for the two Mondays either side of the change:
cat > recurring.py <<'PY'
from datetime import UTC, date, datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo
london = ZoneInfo("Europe/London")
offset_on_booking_day = timezone(timedelta(hours=1))
meeting_time = time(9, 0)
for week in range(2):
day = date(2026, 10, 19) + timedelta(weeks=week)
right = datetime.combine(day, meeting_time, tzinfo=london).astimezone(UTC)
wrong = datetime.combine(day, meeting_time, tzinfo=offset_on_booking_day).astimezone(UTC)
print(f"{day} zone name {right:%H:%M} UTC offset only {wrong:%H:%M} UTC"
f" = {wrong.astimezone(london):%H:%M} London")
PY
uv run recurring.py | tee recurring.outSo for a repeating or far-future event, store the local date and time plus the IANA zone name (Europe/London, not BST or +01:00), and work out the UTC instant for each occurrence when you need it. Zone rules change by law from time to time, so keep tzdata (and the operating system's copy) up to date.
Check it worked
On 19 October both methods give 08:00 UTC. On 26 October the zone name gives 09:00 UTC, while the fixed offset still gives 08:00 UTC, which is 08:00 London: the meeting has slipped an hour early.
Step 4 · Handle clock-change gaps and overlaps with fold
Twice a year a London wall-clock time is ambiguous. On 29 March 2026 the clocks jump from 01:00 to 02:00, so 01:30 never happens (a gap). On 25 October they go back from 02:00 to 01:00, so 01:30 happens twice (an overlap). Python's fold attribute picks which of two readings you mean: fold=0 is the earlier, fold=1 the later.
Write a function that classifies a wall-clock time, and see both cases:
cat > gaps.py <<'PY'
from datetime import UTC, datetime
from zoneinfo import ZoneInfo
london = ZoneInfo("Europe/London")
def classify(wall, zone):
"""Return 'ok', 'gap' or 'overlap' for a naive wall-clock time in a zone."""
earlier = wall.replace(tzinfo=zone, fold=0)
later = wall.replace(tzinfo=zone, fold=1)
if earlier.utcoffset() == later.utcoffset():
return "ok"
# A time inside a gap does not survive a round trip through UTC.
back = earlier.astimezone(UTC).astimezone(zone).replace(tzinfo=None)
return "gap" if back != wall else "overlap"
for wall in (datetime(2026, 7, 15, 15, 0),
datetime(2026, 3, 29, 1, 30),
datetime(2026, 10, 25, 1, 30)):
print(wall, classify(wall, london))
twice = datetime(2026, 10, 25, 1, 30, tzinfo=london)
print("fold=0:", twice.astimezone(UTC).isoformat())
print("fold=1:", twice.replace(fold=1).astimezone(UTC).isoformat())
PY
uv run gaps.py | tee gaps.outzoneinfo does not raise for a time in a gap. It quietly gives you an instant, which then reads back as a different wall-clock time (01:30 becomes 02:30). Decide a policy and code it: here, refuse a booking in a gap and ask the person to pick another time, and take the earlier instant in an overlap while showing the offset so nobody is surprised.
Check it worked
The output marks 15 July ok, 29 March 01:30 gap and 25 October 01:30 overlap, then shows the two real instants behind the repeated 01:30: 00:30 and 01:30 UTC, an hour apart.
Step 5 · Add one day, not 24 hours, when you mean the calendar
"Same time tomorrow" and "in 24 hours" are the same on most days, but not across a clock change. When you add a timedelta to an aware datetime, Python works on the wall clock in that zone. That gives you the calendar meaning, but it also means that subtracting two datetimes in the same zone ignores the clock change:
cat > days.py <<'PY'
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
london = ZoneInfo("Europe/London")
saturday = datetime(2026, 10, 24, 12, 0, tzinfo=london)
next_day = saturday + timedelta(days=1)
plus_24h = (saturday.astimezone(UTC) + timedelta(hours=24)).astimezone(london)
print("one day later: ", next_day.isoformat())
print("24 hours later:", plus_24h.isoformat())
print("same-zone subtraction:", next_day - saturday)
print("real time elapsed: ", next_day.astimezone(UTC) - saturday.astimezone(UTC))
PY
uv run days.py | tee days.outUse the wall-clock sum for reminders and "same time next week". Use UTC for durations, timeouts, billing by the hour and anything else that counts real elapsed time.
Check it worked
One day after Saturday 12:00 is Sunday 12:00, while 24 hours later is Sunday 11:00. The same-zone subtraction claims 1 day, 0:00:00; the UTC subtraction shows the real 1 day, 1:00:00, because that Sunday is 25 hours long in London.
Step 6 · Pass times between systems as ISO 8601 and RFC 9557 strings
Between services, send a time as text, never as a "local" string with no offset. ISO 8601 with an offset (2026-07-15T14:00:00+00:00, or the same with Z) identifies an instant. RFC 9557 extends that format with the zone name in brackets, 2026-07-15T15:00:00+01:00[Europe/London], so the receiver also knows which wall clock the sender meant. Python reads and writes ISO 8601 directly; for the bracket suffix, write two small helpers:
cat > strings.py <<'PY'
from datetime import UTC, datetime
from zoneinfo import ZoneInfo
def to_rfc9557(dt):
return f"{dt.isoformat()}[{dt.tzinfo.key}]"
def from_rfc9557(text):
"""Parse 'stamp[Zone/Name]'. Handles one zone tag, no extra tags."""
stamp, _, rest = text.partition("[")
dt = datetime.fromisoformat(stamp)
zone = ZoneInfo(rest.rstrip("]"))
local = dt.astimezone(zone)
if local.utcoffset() != dt.utcoffset():
raise ValueError(f"offset in {text} does not match {zone.key}")
return local
booked = datetime(2026, 7, 15, 15, 0, tzinfo=ZoneInfo("Europe/London"))
print(booked.astimezone(UTC).isoformat())
print(to_rfc9557(booked))
print(from_rfc9557("2026-07-15T15:00:00+01:00[Europe/London]") == booked)
print(datetime.fromisoformat("2026-07-15T14:00:00Z") == booked)
try:
from_rfc9557("2026-07-15T15:00:00+00:00[Europe/London]")
except ValueError as err:
print("rejected:", err)
PY
uv run strings.py | tee strings.outChecking that the offset matches the zone catches a stale string, for example one written before a country changed its rules.
JavaScript's Temporal API understands RFC 9557 natively. Temporal is on by default in Node.js 26 with no flag; browser support is still arriving, so check MDN's compatibility table before you rely on it in front-end code. Save this as temporal.mjs:
cat > temporal.mjs <<'JS'
const booked = Temporal.ZonedDateTime.from("2026-07-15T15:00:00+01:00[Europe/London]");
console.log(booked.toInstant().toString());
console.log(booked.withTimeZone("Africa/Lagos").toString());
console.log(booked.withTimeZone("Africa/Nairobi").toPlainTime().toString());
const saturday = Temporal.ZonedDateTime.from("2026-10-24T12:00[Europe/London]");
console.log(saturday.add({ days: 1 }).toString());
console.log(saturday.add({ hours: 24 }).toString());
try {
Temporal.ZonedDateTime.from("2026-03-29T01:30[Europe/London]", { disambiguation: "reject" });
} catch (err) {
console.log("gap refused:", err.name);
}
JSnode temporal.mjs | tee temporal.outTemporal keeps the ideas from Python separate in its types: an Instant is a moment, a ZonedDateTime is a moment plus a zone, and add({ days: 1 }) is calendar arithmetic while add({ hours: 24 }) is elapsed time. Its disambiguation option makes the gap policy explicit.
Check it worked
The Python script prints the UTC string, 2026-07-15T15:00:00+01:00[Europe/London], True twice and a rejected: line. The Node script prints 2026-07-15T14:00:00Z, the Lagos time at 15:00:00+01:00, Nairobi's 17:00:00, Sunday at 12:00 and then 11:00, and gap refused: RangeError.
Step 7 · Store meetings in PostgreSQL with timestamptz
PostgreSQL's timestamptz (timestamp with time zone) does not store a time zone. It converts the input to a UTC instant using the offset or zone in the text, stores that, and shows it in the session's TimeZone setting. Plain timestamp silently drops any offset you give it. So the column that holds the instant is timestamptz, and the zone name you need for display or repeats sits in its own column.
Write the SQL:
cat > zones.sql <<'SQL'
CREATE TEMP TABLE meetings (
id int PRIMARY KEY,
title text NOT NULL,
starts_at timestamptz NOT NULL,
time_zone text NOT NULL
);
INSERT INTO meetings VALUES
(1, 'Design review', '2026-07-15 15:00:00+01:00', 'Europe/London'),
(2, 'Payroll check', '2026-10-26 09:00:00 Europe/London', 'Europe/London');
SET TIME ZONE 'UTC';
SELECT id, starts_at FROM meetings ORDER BY id;
SET TIME ZONE 'Africa/Nairobi';
SELECT id, starts_at FROM meetings ORDER BY id;
SELECT id, to_char(starts_at AT TIME ZONE time_zone, 'YYYY-MM-DD HH24:MI') || ' ' || time_zone
FROM meetings ORDER BY id;
SELECT '2026-07-15 15:00:00+01:00'::timestamp;
SQLRun it on your PostgreSQL server. The table is temporary, so it disappears when psql exits:
sudo -u postgres psql -X -q -A -t < zones.sqlSet the database and every connection to UTC, and do display conversion in the application, where you know the viewer's zone. AT TIME ZONE time_zone is handy for reports grouped by the organiser's local day.
Check it worked
You see the two meetings in UTC (14:00:00+00 and 09:00:00+00), then the same instants in Nairobi (17:00:00+03 and 12:00:00+03), then the organiser's local times 2026-07-15 15:00 Europe/London and 2026-10-26 09:00 Europe/London. The last line, 2026-07-15 15:00:00, shows timestamp throwing the +01:00 away.
Step 8 · Turn the rules into a module and tests
Collect the fixes into timekit.py. It takes the wall-clock time a person typed plus their zone name, refuses gaps, picks the earlier instant in overlaps, and refuses to show a naive datetime:
cat > timekit.py <<'PY'
"""Meeting times: store UTC instants plus the organiser's IANA zone name."""
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
class NonexistentTime(ValueError):
"""The wall-clock time falls in a clock-change gap."""
def book(wall, zone_name):
"""Turn a typed wall-clock time into (UTC instant, zone name)."""
if wall.tzinfo is not None:
raise TypeError("pass the wall-clock time without a tzinfo")
zone = ZoneInfo(zone_name)
local = wall.replace(tzinfo=zone, fold=0) # earlier reading in an overlap
if local.astimezone(UTC).astimezone(zone).replace(tzinfo=None) != wall:
raise NonexistentTime(f"{wall:%Y-%m-%d %H:%M} does not exist in {zone_name}")
return local.astimezone(UTC), zone_name
def every_week(local_time, zone_name, first_day, count):
"""UTC instants for a meeting held at the same local time each week."""
return [
book(datetime.combine(first_day + timedelta(weeks=n), local_time), zone_name)[0]
for n in range(count)
]
def show(instant, zone_name):
"""Format a stored instant for a viewer in zone_name."""
if instant.tzinfo is None:
raise TypeError("naive datetime: attach a zone before showing it")
return instant.astimezone(ZoneInfo(zone_name)).strftime("%a %d %b %H:%M %Z")
PYAdd pytest as a development dependency and write one test per rule:
uv add --dev "pytest>=9.2,<10"
cat > test_timekit.py <<'PY'
from datetime import UTC, date, datetime, time, timedelta
from zoneinfo import ZoneInfo
import pytest
from timekit import NonexistentTime, book, every_week, show
def test_stores_a_utc_instant_and_the_zone_name():
instant, zone = book(datetime(2026, 7, 15, 15, 0), "Europe/London")
assert instant == datetime(2026, 7, 15, 14, 0, tzinfo=UTC)
assert zone == "Europe/London"
def test_each_attendee_sees_their_own_wall_clock():
instant, _ = book(datetime(2026, 7, 15, 15, 0), "Europe/London")
assert show(instant, "Africa/Lagos") == "Wed 15 Jul 15:00 WAT"
assert show(instant, "Africa/Nairobi") == "Wed 15 Jul 17:00 EAT"
def test_naive_datetimes_are_refused_for_display():
with pytest.raises(TypeError):
show(datetime(2026, 7, 15, 14, 0), "Africa/Lagos")
def test_a_time_in_the_gap_is_refused():
with pytest.raises(NonexistentTime):
book(datetime(2026, 3, 29, 1, 30), "Europe/London")
def test_an_overlap_takes_the_earlier_instant():
instant, _ = book(datetime(2026, 10, 25, 1, 30), "Europe/London")
assert instant == datetime(2026, 10, 25, 0, 30, tzinfo=UTC)
def test_a_weekly_meeting_keeps_its_local_time_across_the_change():
instants = every_week(time(9, 0), "Europe/London", date(2026, 10, 19), 2)
assert [i.hour for i in instants] == [8, 9]
def test_one_calendar_day_can_be_25_hours():
start = datetime(2026, 10, 24, 12, 0, tzinfo=ZoneInfo("Europe/London"))
end = start + timedelta(days=1)
assert end.astimezone(UTC) - start.astimezone(UTC) == timedelta(hours=25)
PY
uv run pytest -q | tee pytest.outThe tests are the rule set, written so a future change cannot quietly break it:
- Never store or compare naive datetimes. Attach a zone the moment a time enters the program.
- Store past and one-off instants as UTC (
timestamptzin PostgreSQL). - For repeating or far-future events, store the local time and the IANA zone name, and compute instants per occurrence.
- Decide what happens in gaps and overlaps, and test it.
- Use calendar arithmetic for "same time tomorrow" and UTC arithmetic for elapsed time.
- Exchange times as ISO 8601 with an offset, or RFC 9557 when the zone matters.
- Keep
tzdataup to date.
If your users write dates in different languages, keep the stored value in these formats and only translate at the display edge; month and day names belong to the viewer's locale, not to the data.
Check it worked
pytest prints a line of seven dots and 7 passed. To see a test catch a real bug, change fold=0 to fold=1 in timekit.py and run uv run pytest -q again: the overlap test fails. Change it back afterwards.
Step 9 · Clean up
Remove the demo project. Python, uv, Node.js and PostgreSQL stay installed, and the temporary table has already gone:
cd ~
rm -rf ~/tz-demoCheck it worked
ls ~/tz-demo reports No such file or directory.
Next steps
- Times are not the only data that looks the same and is not: understand text encoding, bytes, UTF-8 and Unicode normalisation.
- Grow the test file with fixtures and parametrised cases: test Python code with pytest.
- Join meetings to attendees and their zones in SQL: combine tables with SQL joins.
- Set up the database this tutorial queried: install PostgreSQL 18 on Ubuntu 26.04.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials