Skip to content
Rafe Uddaraj

Time Zones Explained: The Developer's Guide to Getting Time Right

28 min readEnglishRead in Bangla
Time ZonesDate and TimeUTCJavaScriptPython
On this page

At eleven o'clock on the night of Friday, 19 June 2009, every clock in Bangladesh jumped straight to midnight. The government had moved the country one hour ahead to save electricity during a severe power shortage. The next morning, according to the Financial Express, a private airline started its flights an hour late, passengers at Kamalapur railway station missed early trains, and students reached 7 a.m. classes that had already begun.

Six months later, on New Year's Eve, the country changed its mind. When the clocks reached midnight on 31 December, they went back to eleven, and the last hour of 2009 happened twice.

Software had to get through both nights. Every phone, server and booking system that showed the time in Dhaka needed new rules, and those rules were settled only days before they took effect. Most of the time we never think about any of this, because a clock just shows a number. This article is about what that number hides: where time comes from, what a time zone really is, why some clock times never happen and others happen twice, and how to store, send, measure and schedule time so that the next change, whether it comes from a government or from a user in another country, does not catch your code out.

The Three Ideas Behind Every Timestamp

Take a live cricket match. The bowler runs in and releases the ball. That release happens once, at one exact moment, for everyone on the planet. Now look at the clocks. A fan in Dhaka sees the delivery at 3:30 in the afternoon, a fan in Kolkata at 3:00, a fan in Karachi at 2:30. Nobody is wrong. They are all describing the same moment with different labels.

That one scene contains all three ideas:

  1. The instant. The single moment the ball left the bowler's hand. It is a point on one global timeline, the same for everybody. Computers usually store it as a count of time since a fixed starting point.
  2. The wall time. What a clock on a particular wall reads at that instant: "15:30" in Dhaka. On its own, a wall time does not identify a moment, because the same reading occurs in different places at different moments.
  3. The zone rules. The rulebook that turns one into the other for a specific place: "in Dhaka, add six hours to UTC". These rules are decided by governments, and they change.
The three ideas behind every timestamp: an instant, the zone rules, and the wall time; converting an instant to wall time gives one answer, converting wall time to an instant gives zero, one or two
The three ideas behind every timestamp: an instant, the zone rules, and the wall time; converting an instant to wall time gives one answer, converting wall time to an instant gives zero, one or two

Here is the part that most explanations skip, and it is the most useful sentence in this article. Converting instant to wall time always gives exactly one answer: at any given moment, a given clock shows exactly one reading. Converting wall time to instant can give zero, one or two answers. Zero, because on some days a clock skips an hour, so some readings never happen. Two, because on other days a clock repeats an hour, so some readings happen twice. We will meet both later, with real output.

Keep this asymmetry in mind. Almost every rule in the rest of the article follows from it.

Where Time Comes From: Earth, Atoms and UTC

For most of history, time came from the sky. Noon was when the Sun stood highest, and every town had its own noon. When railways and telegraphs arrived, that stopped working, and countries agreed on standard times anchored to Greenwich Mean Time. GMT was the international standard from 1884 until 1972, according to the Royal Museums Greenwich (opens in a new tab). Today the name survives mostly as the winter time zone of the United Kingdom.

The problem with using the Earth as a clock is that the Earth is a slightly unreliable clock. Its spin speeds up and slows down by tiny amounts. Atomic clocks, on the other hand, are almost perfectly steady. So we ended up with three time scales:

  • UT1 follows the Earth's actual rotation. It is the "sky" time.
  • TAI (International Atomic Time) is the average of hundreds of atomic clocks. It never jumps.
  • UTC (Coordinated Universal Time) ticks at the atomic rate of TAI, but it was kept within 0.9 seconds of UT1 by occasionally inserting a leap second, a minute with 61 seconds.
Atomic time ticks perfectly, Earth's rotation wobbles, and UTC follows atomic time but was stepped back with 27 leap seconds between 1972 and 2016; from 20 May 2027 UTC becomes continuous
Atomic time ticks perfectly, Earth's rotation wobbles, and UTC follows atomic time but was stepped back with 27 leap seconds between 1972 and 2016; from 20 May 2027 UTC becomes continuous

Between 1972 and 2016, 27 leap seconds were added. The last one was 2016-12-31T23:59:60Z. TAI started 10 seconds ahead of UTC in 1972, so after 27 leap seconds it is now 37 seconds ahead, as NIST (opens in a new tab) and the IERS leap second table (opens in a new tab) show.

Leap seconds caused so many outages (we will look at several) that the world's timekeepers decided to stop. In 2022 the General Conference on Weights and Measures (CGPM) voted to stop them "in, or before, 2035". Then, in October 2026, it went further:

Resolution 5 of the 28th CGPM (2026): continuous UTC will become effective on 20 May 2027, with a maximum UT1-UTC difference of 3,600 seconds
Resolution 5 of the 28th CGPM (2026): continuous UTC will become effective on 20 May 2027, with a maximum UT1-UTC difference of 3,600 seconds

According to Resolution 5 of the 28th CGPM (opens in a new tab), UTC becomes continuous on 20 May 2027, and UTC is allowed to drift up to one hour away from the Earth's rotation, which the BIPM expects to hold for several centuries. The resolution also explains the urgency. Because the Earth has recently been spinning slightly faster, a negative leap second, removing a second instead of adding one, was becoming likely. Experts put the chance at 30% by 2035. It has never been done, and nobody trusted software to survive it.

What this means for you

If you write application code, the end of leap seconds is good news, and it changes nothing you need to do. What does matter is the next section: your computer's clock was never counting leap seconds in the first place.

Unix Time: The Computer's Stopwatch

Inside almost every computer, an instant is stored as a single number: the count of seconds (or milliseconds) since 00:00:00 UTC on 1 January 1970, a moment called the Unix epoch. Here is the instant from the cricket diagram, written as JavaScript sees it:

JavaScript
const instant = Date.UTC(2026, 10, 29, 12, 0, 0); // months count from 0, so 10 is November
console.log('epoch milliseconds:', instant);
console.log('ISO in UTC :', new Date(instant).toISOString());
CONSOLE
epoch milliseconds: 1795953600000
ISO in UTC : 2026-11-29T12:00:00.000Z

About the examples

Every output block in this article is real. The JavaScript ran on Node.js 24 (the Temporal examples with the --harmony-temporal flag), the Python on 3.15, and the SQL on PostgreSQL 16.

That number has no time zone. It is the same in Dhaka and in New York. Keep this in mind, because it explains a bug we will meet in the next section: a JavaScript Date is not a date with a time zone. It is just this number. The ECMAScript specification (opens in a new tab) defines a Date as a single time value in milliseconds since the epoch. The local time zone only appears when you call methods like getDate() or toString().

Two details are worth knowing.

Unix time pretends leap seconds do not exist. The POSIX definition (opens in a new tab) says every day has exactly 86,400 seconds. When a leap second happened, systems either repeated a second or spread it out. Google "smears" each leap second across 24 hours, from noon to noon UTC, so its clocks run about 11.6 parts per million slow for a day and never show a jump, as described on its leap smear page (opens in a new tab).

Old 32-bit counters run out in 2038. Systems that store Unix seconds in a signed 32-bit integer can count up to 2,147,483,647. Here is what happens next:

JavaScript
const max32 = 2 ** 31 - 1;
console.log('Largest signed 32-bit second:', max32);
console.log('As a date:', new Date(max32 * 1000).toISOString());
console.log('One second later wraps to:', new Date(-(2 ** 31) * 1000).toISOString());
CONSOLE
Largest signed 32-bit second: 2147483647
As a date: 2038-01-19T03:14:07.000Z
One second later wraps to: 1901-12-13T20:45:52.000Z

This is not only a problem for old embedded devices. MySQL's TIMESTAMP column type, for example, still ends at 2038-01-19 03:14:07 UTC according to the MySQL reference manual (opens in a new tab). A 30-year mortgage or a long-lived certificate already reaches past that date.

One Instant, Many Wall Clocks

Let us return to the cricket ball and put real numbers on it. Take the instant 2026-11-29T09:30Z and ask what each local clock shows:

One instant, 09:30 UTC on 29 November 2026, shown on five wall clocks: London 09:30, Karachi 14:30, Kolkata 15:00, Kathmandu 15:15 and Dhaka 15:30
One instant, 09:30 UTC on 29 November 2026, shown on five wall clocks: London 09:30, Karachi 14:30, Kolkata 15:00, Kathmandu 15:15 and Dhaka 15:30

Each clock's distance from UTC is its UTC offset. Offsets are not always whole hours. India uses +05:30, Nepal +05:45, and New Zealand's Chatham Islands +12:45 in winter and +13:45 in summer. You can ask JavaScript's built-in Intl API for any of them:

JavaScript
const at = new Date('2026-11-29T12:00:00Z');
for (const tz of ['UTC', 'Asia/Dhaka', 'Asia/Kolkata', 'Asia/Kathmandu', 'Pacific/Chatham', 'America/New_York', 'Europe/London']) {
const f = new Intl.DateTimeFormat('en-GB', { timeZone: tz, hour: '2-digit', minute: '2-digit', timeZoneName: 'longOffset' });
console.log(tz.padEnd(18), f.format(at));
}
CONSOLE
UTC 12:00 GMT+00:00
Asia/Dhaka 18:00 GMT+06:00
Asia/Kolkata 17:30 GMT+05:30
Asia/Kathmandu 17:45 GMT+05:45
Pacific/Chatham 01:45 GMT+13:45
America/New_York 07:00 GMT-05:00
Europe/London 12:00 GMT+00:00

Look at Chatham: 01:45, and it is already the next day there. Whenever you show an instant to a human, you are choosing one of these clocks. Choosing the wrong one, often the server's, is the most common time bug of all.

Choosing the clock goes wrong in a more surprising place too. Suppose a developer in Dhaka builds an event page. The API returns the event date as "2026-03-08", and the page shows it with new Date("2026-03-08"). On the developer's laptop the page says Sunday, 8 March, and it passes testing. Here is that code run twice on my machine, once pretending to be in New York and once in Dhaka:

CONSOLE
$ TZ=America/New_York node parse.mjs
new Date("2026-03-08") -> Sat Mar 07 2026 19:00:00 GMT-0500 (Eastern Standard Time)
new Date("2026-03-08T00:00") -> Sun Mar 08 2026 00:00:00 GMT-0500 (Eastern Standard Time)
a.getDate(): 7 | b.getDate(): 8
$ TZ=Asia/Dhaka node parse.mjs
new Date("2026-03-08") -> Sun Mar 08 2026 06:00:00 GMT+0600 (Bangladesh Standard Time)
new Date("2026-03-08T00:00") -> Sun Mar 08 2026 00:00:00 GMT+0600 (Bangladesh Standard Time)
a.getDate(): 8 | b.getDate(): 8

Same string, different day. The specification says, word for word, that when there is no offset, "date-only forms are interpreted as a UTC time" while date-time forms are read as local time. So "2026-03-08" becomes midnight UTC, the very start of 8 March in London. For a reader in Dhaka, midnight UTC is 06:00 on the same day. For a reader in New York, it is 19:00 the day before.

JavaScript reads the date-only string 2026-03-08 as midnight UTC, so a user in Dhaka sees 8 March at 06:00 while a user in New York sees 7 March at 19:00, one day earlier
JavaScript reads the date-only string 2026-03-08 as midnight UTC, so a user in Dhaka sees 8 March at 06:00 while a user in New York sees 7 March at 19:00, one day earlier

This is why the bug is so sneaky for developers in Bangladesh, India or anywhere east of UTC: midnight UTC is still "today" for us, so everything looks fine. Every user west of UTC sees yesterday.

The fix

A birthday or an event date has no time and no zone, so do not turn it into an instant at all. Keep it as a plain date: compare the strings, or use Temporal.PlainDate.from("2026-03-08"), or split the string and build the date from its parts. If you must use Date, append a time with no offset ("2026-03-08T00:00") so it is read as local midnight.

An Offset Is Not a Time Zone

Here is a distinction that sounds pedantic until it costs you a meeting. +06:00 and Asia/Dhaka are not the same thing.

An offset is a single number: "six hours ahead of UTC, right now". A time zone is the whole rulebook for a place: which offset applied on every day in the past, and which offset is planned for the future.

Money works the same way. A time zone is like a currency, the Bangladeshi taka. The offset is like today's exchange rate. A UTC timestamp is like an amount already converted into dollars. If you only kept the dollar amount and the rate later changes, you can no longer tell what the original taka price was. If you kept the taka amount and the name of the currency, you can always convert again with whatever the rate turns out to be.

The same goes for abbreviations, which are even worse. "BST" means British Summer Time to a Londoner, but timeanddate lists three different zones (opens in a new tab) under it, including Bangladesh Standard Time. "IST" can mean India, Ireland or Israel. "CST" can mean China or the central United States. An abbreviation is a nickname, not an identifier.

So what is the identifier? A name like Asia/Dhaka, America/New_York or Europe/London. These names come from the most important dataset in this whole story.

The Rulebook: The IANA Time Zone Database

Somewhere, someone has to record that Nepal moved from +05:30 to +05:45 in 1986, that Samoa skipped a whole day in 2011, and that Mexico stopped changing its clocks in 2022. That record is the IANA Time Zone Database, also called tzdb, tz, or the Olson database after its original author.

The IANA Time Zone Database home page, showing release 2026f
The IANA Time Zone Database home page, showing release 2026f

Every phone, laptop, server, browser and programming language that knows about time zones ultimately reads this data. It is maintained by a small group of volunteers under rules set out in RFC 6557 (opens in a new tab), and published by IANA. It works like an official gazette for the world's clocks: governments change the rules, and tzdb records the change so software can follow.

A few things about it are worth knowing:

  • Names are Area/Location. A continent or ocean, then usually the most populous city: Asia/Dhaka, Asia/Kolkata, America/Sao_Paulo. The theory document (opens in a new tab) explains that names are deliberately not country names, because borders and country names change more often than cities move.
  • It changes often. There were 2 releases in 2024, 3 in 2025, and 6 so far in 2026, according to its NEWS file (opens in a new tab). The latest, 2026f, came out on 27 October 2026, partly because Cuba decided not to move its clocks back on 1 November, five days later.
  • Governments often give very little notice. When Mexico abolished daylight saving time in 2022, the Senate voted on 26 October, tzdb published the change on 28 October, and the first clocks affected by it changed on 30 October. In Lebanon in 2023, the government postponed daylight saving time days before it started, many institutions refused to follow, the country briefly ran on two different times, and the decision was reversed within days. tzdb shipped a release to follow the postponement and another, five days later, to undo it.
  • Your software is only as correct as its copy. If a server, container image or phone carries an old copy of tzdb, it will show the wrong local time for every place whose rules changed since.

This is the deepest reason why "just store everything in UTC" is not a complete answer, and Bangladesh has a story that proves it.

The Summer Bangladesh Changed Its Clocks

This article opened on the night of 19 June 2009. Many developers in Bangladesh assume time zones are someone else's problem, since we have one offset, +06:00, and no daylight saving time. Seen from inside the software, that summer is the best lesson there is in how time rules really change.

Asia/Dhaka in 2009: UTC+6 until 19 June at 23:00, then UTC+7 until midnight on 31 December, when the hour from 23:00 to midnight happened twice
Asia/Dhaka in 2009: UTC+6 until 19 June at 23:00, then UTC+7 until midnight on 31 December, when the hour from 23:00 to midnight happened twice

The plan was announced in the spring, but the exact moment of the switch was confirmed only days before it happened. tzdb release 2009i added the rule on 8 June. It contained a mistake, and an Ubuntu developer reported it on the tz mailing list on 15 June, four days before the clocks were due to move:

A tz mailing list post from 15 June 2009 reporting that tzdb 2009i made Asia/Dhaka suddenly switch to UTC after 19 June
A tz mailing list post from 15 June 2009 reporting that tzdb 2009i made Asia/Dhaka suddenly switch to UTC after 19 June

Read the third line from the bottom of that output: after 19 June, the data made Asia/Dhaka jump to an offset of zero. A corrected release, 2009j, went out the same day with a note about the "short turnaround since the DST change is impending". Then, at 23:00 on Friday 19 June, clocks in Bangladesh jumped to midnight.

The Financial Express front page story from 21 June 2009 on how daylight saving time caught people by surprise
The Financial Express front page story from 21 June 2009 on how daylight saving time caught people by surprise

That is the Financial Express (opens in a new tab) report of the first day, the source of the late flights, missed trains and missed classes from the start of this article.

The ending was messier still. Daylight saving was supposed to end on 30 September, but that plan was dropped and it continued indefinitely. Then the government decided, around 23 December, to end it at midnight on 31 December. tzdb published release 2009u on 26 December, five days before the change. You can see the result in today's data. This Python script walks through 2009 and prints every moment the offset of Asia/Dhaka changed:

Python
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
dhaka = ZoneInfo("Asia/Dhaka")
t = datetime(2009, 1, 1, tzinfo=timezone.utc)
prev = t.astimezone(dhaka).utcoffset()
while t.year == 2009:
off = t.astimezone(dhaka).utcoffset()
if off != prev:
print("UTC", t.strftime("%Y-%m-%d %H:%M"), "| Dhaka offset", prev, "->", off,
"| local clock shows", t.astimezone(dhaka).strftime("%Y-%m-%d %H:%M %z"))
prev = off
t += timedelta(minutes=30)
CONSOLE
UTC 2009-06-19 17:00 | Dhaka offset 6:00:00 -> 7:00:00 | local clock shows 2009-06-20 00:00 +0700
UTC 2009-12-31 17:00 | Dhaka offset 7:00:00 -> 6:00:00 | local clock shows 2009-12-31 23:00 +0600

Look at the second line. At 24:00 on New Year's Eve 2009, the clock went back to 23:00. Every minute between 23:00 and midnight on 31 December 2009 happened twice in Dhaka. Any system that recorded "local time only" for New Year's Eve transactions has entries it cannot put in order.

Now picture an app that let users book appointments in May 2009, before any of this was decided. Here is what happens if it converts each booking to UTC at the moment of booking, using the rules it knows at that moment:

Python
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo
# May 2009: a user in Dhaka books a meeting for 1 July 2009, 10:00 local.
# The app converts it to UTC using the rules it knows at booking time: +06:00.
booked_local = datetime(2009, 7, 1, 10, 0)
rules_at_booking = timezone(timedelta(hours=6))
stored_utc = booked_local.replace(tzinfo=rules_at_booking).astimezone(timezone.utc)
print("stored in the database :", stored_utc.isoformat())
# June 2009: Bangladesh moves its clocks to +07:00. On 1 July the app shows the stored UTC value in local time.
shown = stored_utc.astimezone(ZoneInfo("Asia/Dhaka"))
print("shown to the user :", shown.isoformat())
# The alternative: keep the wall time and the zone name, and resolve the instant when you need it.
wall = datetime(2009, 7, 1, 10, 0, tzinfo=ZoneInfo("Asia/Dhaka"))
print("wall time + zone :", wall.isoformat(), "=", wall.astimezone(timezone.utc).isoformat())
CONSOLE
stored in the database : 2009-07-01T04:00:00+00:00
shown to the user : 2009-07-01T11:00:00+07:00
wall time + zone : 2009-07-01T10:00:00+07:00 = 2009-07-01T03:00:00+00:00

The meeting the user booked for 10:00 now shows as 11:00. The database did nothing wrong. It faithfully stored an instant that was calculated with rules that later changed.

A meeting booked in May 2009 for 10:00 Dhaka time and stored as 04:00 UTC shows up as 11:00 after Bangladesh moved to UTC+7; storing the wall time and the zone name keeps it at 10:00
A meeting booked in May 2009 for 10:00 Dhaka time and stored as 04:00 UTC shows up as 11:00 after Bangladesh moved to UTC+7; storing the wall time and the zone name keeps it at 10:00

Wedding invitations already solve this problem. A card says "Reception, 7 p.m., at the hall in Dhaka". If the government moves the clocks before the wedding, guests still arrive when the hall's clock says 7 p.m. Nobody recalculates the card into UTC. The card records what people agreed on, and the actual instant is worked out on the day, with that day's rules. That is exactly how software should treat future events, and we will turn it into a rule in the storage section.

Daylight Saving: Times That Never Happen, Times That Happen Twice

Bangladesh tried daylight saving once. About 70 countries still use it, fewer than 40% of all countries, according to timeanddate's statistics (opens in a new tab). That includes most of Europe and North America, where a large share of your users and many cloud regions live.

In New York in 2026, clocks jumped forward on Sunday 8 March and went back on Sunday 1 November:

Daylight saving in New York, 2026: on 8 March the wall clock jumps from 01:59 to 03:00 so 02:30 never happens; on 1 November the hour from 01:00 to 01:59 happens twice, first at UTC-4 then at UTC-5
Daylight saving in New York, 2026: on 8 March the wall clock jumps from 01:59 to 03:00 so 02:30 never happens; on 1 November the hour from 01:00 to 01:59 happens twice, first at UTC-4 then at UTC-5

A book with misprinted page numbers behaves the same way. In spring, the printer jumps from page 1 to page 3. If someone asks you to open page 2, there is no such page: that is the gap. In autumn, the printer prints page 1 twice. If someone asks you to open page 1, you have to ask which one: that is the overlap. This is exactly the "zero or two answers" problem from the start of the article.

The modern JavaScript date API, Temporal, makes you face this choice explicitly. Temporal reached Stage 4 at TC39 in March 2026 and ships in Firefox 139, Chrome 144 and Node.js 26. Safari has not shipped it in a stable release yet, so browser code still needs the @js-temporal/polyfill package for now. Here is what it does with the gap, the overlap, and a day that is not 24 hours long:

JavaScript
// node --harmony-temporal dst.mjs (Node.js 26 and later need no flag)
const zone = 'America/New_York';
// 1. A wall-clock time that never happens (spring forward, 8 March 2026)
const gap = { year: 2026, month: 3, day: 8, hour: 2, minute: 30 };
for (const disambiguation of ['compatible', 'earlier', 'later']) {
const z = Temporal.ZonedDateTime.from({ ...gap, timeZone: zone }, { disambiguation });
console.log(`gap ${disambiguation.padEnd(10)} ->`, z.toString());
}
try {
Temporal.ZonedDateTime.from({ ...gap, timeZone: zone }, { disambiguation: 'reject' });
} catch (e) {
console.log('gap reject ->', e.name);
}
// 2. A wall-clock time that happens twice (fall back, 1 November 2026)
const overlap = { year: 2026, month: 11, day: 1, hour: 1, minute: 30 };
for (const disambiguation of ['earlier', 'later']) {
const z = Temporal.ZonedDateTime.from({ ...overlap, timeZone: zone }, { disambiguation });
console.log(`overlap ${disambiguation.padEnd(7)} ->`, z.toString(), '=', z.toInstant().toString());
}
// 3. "One day later" is not always 24 hours
const sat = Temporal.ZonedDateTime.from('2026-03-07T09:00[America/New_York]');
console.log('Saturday 09:00 ->', sat.toString());
console.log('+ { days: 1 } ->', sat.add({ days: 1 }).toString());
console.log('+ { hours: 24 } ->', sat.add({ hours: 24 }).toString());
console.log('hours in that Sunday ->', sat.add({ days: 1 }).hoursInDay);
CONSOLE
gap compatible -> 2026-03-08T03:30:00-04:00[America/New_York]
gap earlier -> 2026-03-08T01:30:00-05:00[America/New_York]
gap later -> 2026-03-08T03:30:00-04:00[America/New_York]
gap reject -> RangeError
overlap earlier -> 2026-11-01T01:30:00-04:00[America/New_York] = 2026-11-01T05:30:00Z
overlap later -> 2026-11-01T01:30:00-05:00[America/New_York] = 2026-11-01T06:30:00Z
Saturday 09:00 -> 2026-03-07T09:00:00-05:00[America/New_York]
+ { days: 1 } -> 2026-03-08T09:00:00-04:00[America/New_York]
+ { hours: 24 } -> 2026-03-08T10:00:00-04:00[America/New_York]
hours in that Sunday -> 23

Read it slowly, because each line teaches something:

  • 02:30 on 8 March does not exist. compatible (the default, which matches how the old Date behaves) moves it forward to 03:30. earlier gives 01:30. reject throws, which is what you want when a user types a time into a booking form and you need to tell them it does not exist.
  • 01:30 on 1 November exists twice, one hour apart: 05:30 UTC and 06:30 UTC. Same wall time, two different instants.
  • "One day later" and "24 hours later" are different questions. Adding one day to Saturday 09:00 gives Sunday 09:00. Adding 24 hours gives Sunday 10:00, because that Sunday was only 23 hours long. Your "remind me at the same time tomorrow" feature wants days. Your "token expires in 24 hours" feature wants hours.

Python solves the overlap the same way with a fold attribute, added in Python 3.6 by PEP 495 (opens in a new tab). fold=0 means the first occurrence and fold=1 means the second:

Python
from datetime import datetime
from zoneinfo import ZoneInfo
ny = ZoneInfo("America/New_York")
for fold in (0, 1):
t = datetime(2026, 11, 1, 1, 30, tzinfo=ny, fold=fold)
print(f"fold={fold}:", t.isoformat(), "->", t.astimezone(ZoneInfo("UTC")).isoformat())
CONSOLE
fold=0: 2026-11-01T01:30:00-04:00 -> 2026-11-01T05:30:00+00:00
fold=1: 2026-11-01T01:30:00-05:00 -> 2026-11-01T06:30:00+00:00

How to Store Time

We now have everything we need to answer the question this whole subject comes down to: what should go in the database? The answer depends on what the value means, and there are four cases.

Decision guide for storing time: a moment that already happened is stored as an instant; a future human event is stored as wall time plus an IANA zone with UTC derived; a calendar date with no time is stored as a plain date; a length of time is stored as a duration
Decision guide for storing time: a moment that already happened is stored as an instant; a future human event is stored as wall time plus an IANA zone with UTC derived; a calendar date with no time is stored as a plain date; a length of time is stored as a duration

1. Something that already happened: store the instant. When an order was paid, when a user logged in, when a log line was written. These moments are fixed forever, and no future rule change can move them. Store them in UTC, or in a type that means "an instant", such as PostgreSQL's timestamptz. This is where "always use UTC" is completely right.

2. A future event that people will attend: store the wall time and the zone name. A meeting, a flight, an exam, a reminder. Store what the person actually chose, 2026-12-15 10:00 and Asia/Dhaka, and compute the UTC instant from it when you need it. You can keep a UTC copy for sorting and querying, but treat it as a cache that you recompute when tzdb changes, never as the source of truth. Jon Skeet's Storing UTC is not a silver bullet (opens in a new tab) and Simon Willison's Storing times for human events (opens in a new tab) both reach this conclusion, and our Bangladesh example shows why.

3. A date with no time: store a plain date. Birthdays, holidays, invoice due dates. A birthday is not an instant. It is the same "15 March" everywhere in the world. Converting it to midnight UTC is exactly what moved the event page to the wrong day earlier.

4. A length of time: store a duration. "Session lasts 30 minutes", "request took 120 ms". A duration has no zone at all.

Databases make it easy to get case 1 subtly wrong, because their type names are misleading. Here is PostgreSQL storing the same meeting in its two timestamp types, then reading it back after the session moves to a different zone:

SQL
SET TimeZone = 'America/New_York';
CREATE TABLE meetings (title text, at_plain timestamp, at_tz timestamptz);
INSERT INTO meetings VALUES ('standup', '2026-03-10 09:00', '2026-03-10 09:00');
SELECT title, at_plain, at_tz FROM meetings;
SET TimeZone = 'Asia/Dhaka';
SELECT title, at_plain, at_tz FROM meetings;
CONSOLE
title | at_plain | at_tz
---------+---------------------+------------------------
standup | 2026-03-10 09:00:00 | 2026-03-10 09:00:00-04
(1 row)
title | at_plain | at_tz
---------+---------------------+------------------------
standup | 2026-03-10 09:00:00 | 2026-03-10 19:00:00+06
(1 row)

timestamp (without time zone) kept the text "09:00" and has no idea which 09:00 it was. timestamptz correctly kept the instant, 09:00 in New York is 19:00 in Dhaka, but notice what it did not keep: the fact that the meeting was set in New York. The PostgreSQL documentation (opens in a new tab) says so directly: the value is stored internally as UTC, and the originally stated time zone is not retained. Despite its name, timestamp with time zone stores no time zone.

So the practical recipe in PostgreSQL is:

  • Past events: timestamptz. The PostgreSQL wiki's Don't Do This (opens in a new tab) page makes this its rule for points in time.
  • Future human events: a timestamp column for the wall time plus a text column for the IANA zone name, with an optional timestamptz column computed from them for sorting.
  • Plain dates: date.
  • Durations: interval, or an integer number of milliseconds.

And one rule that applies everywhere: never store an offset (+06:00) or an abbreviation (BST) where you mean a zone. Store the IANA name.

How to Send Time Between Systems

When time travels between a server, an API and a browser, it travels as text, and the text format decides whether meaning survives the trip.

The safe format is defined by RFC 3339 (opens in a new tab), a strict profile of ISO 8601. An instant should always carry its offset, or Z for UTC:

Text
2026-11-29T12:00:00Z an instant, in UTC
2026-11-29T18:00:00+06:00 the same instant, written with Dhaka's offset
2026-11-29T18:00:00 ambiguous: a wall time with no zone, avoid for instants
2026-11-29 a plain date, fine for birthdays, wrong for instants

An offset tells the receiver the instant, but not the place. For future events that is not enough, as we saw. RFC 9557 (opens in a new tab), published in April 2024, extends the format with the zone name in square brackets, and it is the same format Temporal prints:

Text
2026-12-15T10:00:00+06:00[Asia/Dhaka]

Now the receiver has the wall time, the offset that applied when it was written, and the rulebook to recompute it if the rules change.

In practice:

  • Make your API send instants as RFC 3339 strings with Z or an offset, never a bare local time.
  • For future events, send the wall time and the IANA zone name, either as the RFC 9557 form or as two separate fields.
  • Send plain dates as YYYY-MM-DD, and make sure the client never turns them into instants.
  • Send durations as numbers with a unit in the field name (timeoutMs), or as ISO 8601 durations such as PT30M.

How to Measure Time

There is one more kind of clock we have not met, and it matters every time you measure how long something took.

The wall clock of a computer, the one that tells you it is 12:00, is not steady. NTP, the protocol that keeps it accurate, sometimes steps it forward or backward to correct drift. The Linux clock documentation (opens in a new tab) describes the real-time clock as settable and affected by those jumps. If the clock is stepped back in the middle of a measurement, end minus start can come out negative.

A monotonic clock only ever moves forward. Its value means nothing on its own, it is not a date, but the difference between two readings is always a real duration.

Example: a request takes 500 milliseconds, but the wall clock is stepped back one second in the middle, so end minus start on the wall clock is minus 500 milliseconds while the monotonic clock correctly measures 500 milliseconds
Example: a request takes 500 milliseconds, but the wall clock is stepped back one second in the middle, so end minus start on the wall clock is minus 500 milliseconds while the monotonic clock correctly measures 500 milliseconds

Nobody times a race with the office wall clock, the one someone occasionally walks up to and corrects. Races are timed with a stopwatch, which only counts.

This is not theoretical. During the leap second on 1 January 2017, Cloudflare's DNS service computed a duration as time.Now().Sub(start), the wall clock went backward, the duration came out negative, and a function that expected a positive number panicked. Their postmortem (opens in a new tab) explains how at the peak about 0.2% of DNS queries failed. Go 1.9, released later that year, added a monotonic reading to every value returned by time.Now(), and the time package documentation (opens in a new tab) explains that comparisons and subtractions now use it automatically.

In each language, use the monotonic clock for durations:

JavaScript
const start = performance.now(); // monotonic milliseconds, not a date
await doWork();
const tookMs = performance.now() - start;
Python
import time
start = time.monotonic()
do_work()
took_seconds = time.monotonic() - start

The same idea protects distributed systems. If you have read my article on distributed locks and fencing tokens, you have already seen how lease timeouts break when clocks jump. Measure timeouts with monotonic time, and never trust two machines' wall clocks to agree exactly.

How to Schedule Time

Scheduling combines everything at once, because a schedule is a promise about future wall times.

Recurring events need a zone, not an offset. A standup "every weekday at 09:00 in New York" must move from 14:00 UTC to 13:00 UTC when daylight saving starts, so the people in New York keep meeting at 09:00. That is why the calendar standard, RFC 5545 (opens in a new tab) (iCalendar), attaches a TZID to event times, and why the Google Calendar API requires a timeZone for recurring events, the zone "in which the recurrence is expanded". RFC 5545 also says what happens when a recurrence lands on a time that does not exist: that occurrence is ignored and not counted.

Cron jobs and daylight saving do not mix well. If a job is scheduled for 02:30 local time in a zone with daylight saving, it falls into the gap once a year and into the overlap once a year. Implementations differ. The common Linux cron daemon, cronie, has special handling (opens in a new tab) for clock changes of less than three hours, but only for jobs at a fixed time: skipped jobs run right away, and repeated ones are not run twice. Jobs with wildcards get no special handling. Other schedulers behave differently.

The safest rule is: run servers and schedulers in UTC, and do the time zone math in your application, where you can test it. If a schedule truly must follow local time, say so explicitly. Kubernetes CronJobs, for example, have a timeZone field that is stable since Kubernetes 1.27 (opens in a new tab):

YAML
apiVersion: batch/v1
kind: CronJob
metadata:
name: daily-report
spec:
schedule: "0 9 * * *"
timeZone: "Asia/Dhaka"
jobTemplate:
spec:
template:
spec:
containers:
- name: report
image: example/report:1.0
restartPolicy: OnFailure

And schedule anything that must not run twice or be skipped away from the gap and overlap hours, which in most zones fall between 00:00 and 03:00 local time on transition days.

The Same Ideas in Every Language

One reason this subject feels confusing is that every ecosystem uses different names for the same three ideas. Here is the map:

IdeaJavaScript (Temporal)Java (java.time)PythonGoPostgreSQL
InstantTemporal.InstantInstantaware datetime in UTCtime.Timetimestamptz
Wall time and date, no zoneTemporal.PlainDateTimeLocalDateTimenaive datetime(no separate type)timestamp
Date onlyTemporal.PlainDateLocalDatedate(no separate type)date
Instant with zone rulesTemporal.ZonedDateTimeZonedDateTimeaware datetime with ZoneInfotime.Time with *time.Locationwall timestamp plus a zone column
Fixed offset onlyan offset stringOffsetDateTimedatetime with timezone(timedelta)time.FixedZone(avoid)
DurationTemporal.DurationDuration, Periodtimedeltatime.Durationinterval

A few language-specific notes worth knowing:

  • JavaScript: the old Date is an instant with a local-time view bolted on. Prefer Temporal (or its polyfill) for anything involving zones or calendar arithmetic.
  • Python: a datetime without tzinfo is "naive" and means nothing more than a wall-clock reading. datetime.utcnow() returns a naive value and has been deprecated since Python 3.12. Use datetime.now(timezone.utc) instead. Running it on Python 3.15 with warnings enabled says so:
CONSOLE
$ python3 -W error -c "import datetime; datetime.datetime.utcnow()"
DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
  • Java: java.time already has the full model. LocalDateTime is the plain wall time, ZonedDateTime carries the rules, OffsetDateTime carries only an offset.
  • Go: time.Time always carries a location and, from time.Now(), a monotonic reading. Load zones with time.LoadLocation("Asia/Dhaka"), and make sure your container image includes zone data or import the time/tzdata package.

When Time Broke Production

Every rule above was written in someone's outage report. Here are some of the best documented:

WhenWhat happenedThe lesson
31 Dec 2008Microsoft's Zune 30GB music players froze worldwide; Microsoft blamed the clock driver's handling of the 366th day of a leap year (Engadget (opens in a new tab))Test the last day of a leap year
31 Oct 2010Repeating iPhone alarms went off an hour late in Europe after clocks went back (MacRumors (opens in a new tab))Test schedules across transitions
29 Feb 2012Azure computed certificate expiry by adding one to the year, producing 29 February 2013, a date that does not exist, and a large outage followed (Microsoft (opens in a new tab))Use calendar arithmetic from a library, never by hand
30 Jun 2012A leap second triggered a Linux kernel bug; Reddit, Mozilla and LinkedIn were hit, and airline check-in systems went down for about an hour (The Register (opens in a new tab))A minute can have 61 seconds
1 Jan 2017Cloudflare DNS failures from a negative duration measured with the wall clock (Cloudflare (opens in a new tab))Measure durations with a monotonic clock
29 Feb 2024Card payments at self-service fuel pumps across New Zealand failed for more than ten hours because of a leap day bug at a payment provider (RNZ (opens in a new tab))Leap days still break software in 2024

Notice that almost none of these were exotic. A leap day. A clock going back. A minute with one extra second. They are rare enough that nobody tests them, and common enough that they always arrive eventually.

Assumptions That Break

The assumptionWhat actually happens
"My country has no daylight saving time, so I don't need to care."Bangladesh had it in 2009. Your users, servers and cloud regions live in other zones, whose rules can change with a few days' notice.
"Just store everything in UTC."Right for things that already happened. Wrong as the only copy of a future event, because the conversion depends on rules that may change first.
"A day has 24 hours."In New York, 8 March 2026 had 23 hours and 1 November 2026 had 25.
"An offset tells me the time zone."+06:00 is shared by Bangladesh, Bhutan, Kyrgyzstan and parts of other countries, and says nothing about their rules next year.
"The server's local time is fine."A server's zone is an accident of where it runs. Run servers in UTC and convert at the edges, for each user.
"Leap seconds are my problem."Not for new code: UTC becomes continuous on 20 May 2027. Keep using monotonic clocks anyway, because NTP still steps clocks.

A Review List for Code That Touches Time

When the code...Make sure it...
records something that already happenedstores an instant: timestamptz or UTC
saves a meeting, flight, exam or reminderstores the wall time and an IANA zone name, with UTC only as a cache to recompute
handles a birthday, holiday or due datekeeps a plain date and never converts it to midnight UTC
sends time to another systemuses RFC 3339 with Z or an offset, plus the zone name for future events
parses a date string in JavaScriptnever turns a date-only string into an instant
adds days, months or hoursuses a real library (Temporal, java.time, zoneinfo, Noda Time), not hand-written arithmetic
measures how long something tookuses a monotonic clock: performance.now(), time.monotonic()
runs on a scheduleruns in UTC, or names its zone explicitly
ships in a container or appcarries an up-to-date tzdb

And test the hard days: the gap and overlap days of your users' zones, 29 February, 31 December of a leap year, and users both east and west of UTC.

On New Year's Eve 2009, a clock in Dhaka showed 23:30 twice. Both readings were correct, and they named two different moments. That is the whole subject in one picture: a clock reading is only a label, and the moment underneath it, the place it belongs to, and the rules that connect them are three separate things. Keep them separate in your code, and the next government announcement becomes a data update instead of an outage.

References

All articles

Get in touch

Questions about a video, an article, or working together.