Computer Time

Time: Clocks, Calendars and How We Measure It

Course 1 ยท Chapter 11 ยท Keeping computers on time

A computer has no sense of the present. It has a counter that someone started once, a crystal that ticks it forward (the same sort of crystal as in Time: Clocks, Calendars and How We Measure It 10), and a habit of asking other machines whether it is right. Everything it "knows" about dates, from file timestamps to calendar invitations to bank transactions, is built on top of that counter. This chapter looks at how the counter is arranged, why one famous deadline in January 2038 worries engineers, why the world's civil time sometimes gains a second, how a network keeps millions of clocks in step, and why time zones are the part of the job that programmers dread most.

What was run, and what to trust
Every Python snippet in this chapter and in the three exercise solutions was executed, and the output in the comments is what Python printed. The history and the figures about leap seconds, the 2038 limit and the date bugs are quoted from the standard accounts; the arithmetic is worked in the text. Time zone rules change from year to year, so the outputs for 2027 reflect the rules as of this writing.

Unix Time: Seconds Since 1970

The simplest way to store a moment is as one number: how many seconds have passed since a fixed starting point. The Unix operating system, developed in the early 1970s, chose midnight at the start of 1 January 1970, UTC, called the epoch. A timestamp of 0 means that instant, 86,400 means a day later, and so on. A number is easy to store, compare and subtract: the gap between two events is just one value minus the other, with no months or leap years to worry about. That one idea is now everywhere, in phones, web servers and databases.

Turning the number back into a calendar date is a division. Take the timestamp 1,700,000,000. Dividing by 86,400 gives 19,675 whole days with 80,000 seconds left over. The leftover is 22 hours (79,200 seconds), 13 minutes (780 seconds) and 20 seconds, so the time of day is 22:13:20. And 19,675 days after 1 January 1970 is 14 November 2023. Together: 14 November 2023, 22:13:20 UTC.

from datetime import datetime, timedelta, timezone epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) days, secs = divmod(1_700_000_000, 86400) print(days, secs, secs // 3600, secs % 3600 // 60, secs % 60) print(epoch + timedelta(days=days)) # 19675 80000 22 13 20 # 2023-11-14 00:00:00+00:00

The Year 2038 Problem

Early Unix stored the counter in a 32-bit signed whole number: 32 binary digits, one of which says plus or minus. The largest value such a number can hold is 231 − 1 = 2,147,483,647. Count that many seconds from the epoch and you reach 03:14:07 UTC on 19 January 2038. One second later the number overflows and wraps round to −2,147,483,648, which a program reads as 20:45:52 on 13 December 1901. Systems that still keep time in a signed 32-bit field would suddenly jump back about 137 years.

biggest = 2 ** 31 - 1 print(biggest) print(epoch + timedelta(seconds=biggest)) print(biggest - 1_700_000_000, "seconds left after that 2023 timestamp =", round((biggest - 1_700_000_000) / 86400 / 365.2425, 1), "years") # 2147483647 # 2038-01-19 03:14:07+00:00 # 447483647 seconds left after that 2023 timestamp = 14.2 years

The fix is simple in principle: store the count in 64 bits. A signed 64-bit counter lasts roughly 292 billion years, many times the age of the universe, so it will not wrap in practice. Modern operating systems already use 64 bits, and the hard part is finding the old places that do not: embedded controllers in cars and factory machines, file formats and databases with 32-bit time fields, and long-lived software nobody remembers. The situation resembles the famous Year 2000 problem, where years stored as two digits made 2000 look like 1900, except that this date has been known for decades.

CounterLargest valueRuns out
Signed 32-bit2,147,483,64719 January 2038
Unsigned 32-bit4,294,967,2957 February 2106
Signed 64-bitabout 9.2 × 1018about 292 billion years from 1970

UTC and Leap Seconds

Time: Clocks, Calendars and How We Measure It 9 described Greenwich time as the world's standard, and Time: Clocks, Calendars and How We Measure It 10 showed that the second is now an atomic count. These two ideas pull in slightly different directions. Atomic clocks tick at a perfectly steady rate. The spinning Earth does not: tides and movements inside the planet make the day vary by a few thousandths of a second, and over centuries the day has been getting a little longer. If we kept only atomic time, noon on the clock would slowly drift away from the Sun.

Coordinated Universal Time (UTC) is the compromise. It ticks at the atomic rate, but is kept within 0.9 seconds of the Earth's rotation by adding an occasional leap second, announced by an international body some months ahead. On the chosen day the last minute of the day, normally 60 seconds, is given 61, shown as 23:59:60. The first leap second was added on 30 June 1972, and 27 have been added altogether, the most recent at the end of 2016. On 1 January 1972, atomic time (TAI) was 10 seconds ahead of UTC, so after 27 more it is 10 + 27 = 37 seconds ahead. GPS time started on 6 January 1980, when the gap was already 19 seconds, and does not use leap seconds, so GPS time is now 37 − 19 = 18 seconds ahead of UTC.

leaps = 27 print("TAI minus UTC:", 10 + leaps, "s") print("GPS minus UTC:", 10 + leaps - 19, "s") print("seconds in a day with a leap second:", 86400 + 1) # TAI minus UTC: 37 s # GPS minus UTC: 18 s # seconds in a day with a leap second: 86401

Leap seconds are a headache for software. Unix time pretends every day has exactly 86,400 seconds, so it has no way to write 23:59:60: the counter either repeats a second or stalls briefly, and some systems have misbehaved at a leap second. Some large operators therefore "smear" the extra second, stretching it across many hours so no clock ever sees a 61-second minute. Because of these troubles, the international measures body decided in 2022 that leap seconds should be dropped by 2035, letting UTC drift a little from the Sun instead; exactly how is still being worked out.

Drift and the Network Time Protocol

A computer's quartz clock is not very good. The crystal ranks with the cheap quartz of Time: Clocks, Calendars and How We Measure It 10, and in a warm server room it might be 10 to 50 ppm off. A 50 ppm error is 50 × 0.0864 = 4.32 seconds a day, and it also changes as the machine heats up and cools down. Left alone, a computer's clock would wander by seconds a day.

The cure is the Network Time Protocol (NTP), designed by David Mills in the 1980s and still in use. Machines are arranged in layers called strata: stratum 0 is the reference clock itself (an atomic clock or a GPS receiver), stratum 1 servers are wired directly to one, stratum 2 machines ask stratum 1, and so on. A client does not just ask "what time is it?", because the answer would be out of date by the time it arrives. Instead it records four timestamps:

client server t0 ---- request ----------> t1 (server clock when it arrives) t3 <--- reply ------------ t2 (server clock when it leaves) round trip = (t3 - t0) - (t2 - t1) clock offset = ((t1 - t0) + (t2 - t3)) / 2

The round trip is the time spent travelling, with the server's thinking time removed. Averaging the outward and return differences cancels the journey time, provided the trip took about the same each way, and leaves how far the client clock is from the server's. Here is an example in which the client really is half a second behind, and each leg takes 0.05 s:

t0, t1, t2, t3 = 100.000, 100.550, 100.551, 100.101 print(round((t3 - t0) - (t2 - t1), 3)) print(round(((t1 - t0) + (t2 - t3)) / 2, 3)) # 0.1 # 0.5

The sums check out: (0.550 + 0.450) / 2 = 0.5, a client half a second behind, and a round trip of 0.101 − 0.001 = 0.1 s. A client asks several servers, throws away the odd ones, and rather than jumping the clock it usually nudges it gently faster or slower, so that time never appears to run backwards. Over the internet NTP typically holds clocks to within a few milliseconds; on a local network, a fraction of a millisecond. GPS receivers do far better, to tens of nanoseconds, as Time: Clocks, Calendars and How We Measure It 10 explained, which is why phone masts and power grids use them.

Time sourceTypical accuracyUsed by
Uncorrected computer clockseconds a daynothing sensible
NTP over the interneta few millisecondslaptops, phones, ordinary servers
NTP on a local networkunder a millisecondoffices, data centres
GPS receivertens of nanosecondsphone masts, power grids, exchanges

Time Zones: The Database Behind the Names

UTC and Unix time are tidy. People are not: they want to know the local time, and Time: Clocks, Calendars and How We Measure It 9 showed how the rules came about. Every country decides its own offset from UTC and whether to use daylight saving, and they change the rules often, sometimes with only a few weeks' notice. Programmers cannot simply add a fixed number of hours, because the number depends on the place and the date.

The answer is a shared catalogue, the time zone database (often called tz or zoneinfo, begun in the 1980s by Arthur David Olson and now maintained as a public service by the Internet Assigned Numbers Authority). It lists every region's history of offsets and daylight saving rules, named by continent and city: Europe/London, Asia/Kolkata, America/New_York. It uses a city rather than a "GMT+1" label because one offset can belong to several rule sets, and the same city may change its offset over time. Updating a phone or server often includes a fresh copy of this one file.

from zoneinfo import ZoneInfo m = datetime(2027, 1, 15, 12, 0, tzinfo=timezone.utc) for n in ("Europe/London", "Asia/Kolkata", "America/New_York"): print(n, m.astimezone(ZoneInfo(n)).strftime("%H:%M %Z %z")) # Europe/London 12:00 GMT +0000 # Asia/Kolkata 17:30 IST +0530 # America/New_York 07:00 EST -0500

The golden rule is: store UTC, convert only for display. If you store a local time, you cannot always tell which moment was meant. On the night clocks go back, the hour from 01:00 to 02:00 happens twice; on the night they go forward, an hour does not exist at all. A stored "01:30" is then ambiguous or impossible. A UTC value (or a Unix timestamp) names exactly one instant and can be shown correctly anywhere. India's half-hour offset above is a reminder, too, that zones are not always whole hours (Nepal uses 45 minutes past the hour).

Classic Date Bugs

Because time is so easy to get subtly wrong, programmers keep a collection of famous failures. A few that you can work out for yourself:

BugWhat went wrongThe sum
Year 2000years stored as two digits, so 00 looked like 19001900 + 0 = 1900, not 2000
Leap-year rule"every four years" with no century exception calls 1900 a leap year (Time: Clocks, Calendars and How We Measure It 4 gave the full rule)1900 ÷ 4 = 475, but 1900 ÷ 100 = 19 and 1900 ÷ 400 is not whole
248-day countera counter of hundredths of a second in a signed 32-bit number; a passenger aircraft's control units were reported in 2015 to need a restart before this limit231 ÷ 100 ÷ 86,400 = 248.55 days
GPS week rolloverthe satellite message counts weeks in 10 binary digits, so it wraps after 1,024 weeks; receivers that did not allow for it showed the wrong date after the rollovers of 1999 and 20191,024 × 7 ÷ 365.24 = 19.6 years
print(round(2 ** 31 / 100 / 86400, 2), "days") print(round(1024 * 7 / 365.2425, 1), "years") # 248.55 days # 19.6 years

The pattern is the same each time: a counter too small, a rule too simple, or a local time stored where a universal one was needed. Hence the standing advice to use well-tested date libraries rather than writing your own, to keep clocks synchronised, and to ask "what happens at the edges?" (midnight, the end of February, the clock change, the end of the counter).

Common mistakes
Saying Unix time "counts leap seconds" (it does not: every Unix day is exactly 86,400 seconds); storing local times without the zone; adding 24 hours to mean "tomorrow" when a clock change falls in between; assuming every offset is a whole number of hours; and thinking the 2038 limit affects any system that already uses 64-bit time (it does not, but older software on it may still carry 32-bit fields).
Exercise 1

Use Python to turn the timestamps 0, 86400, 1,000,000,000 and 1,700,000,000 into UTC dates. Find the largest signed 32-bit value and the exact UTC second it reaches, the date a wrapped counter would show one second later, and how long signed 32-bit, unsigned 32-bit and signed 64-bit counters last from 1970.

๐Ÿ“„ View solution
Exercise 2

Work out the daily drift of a 10 ppm and a 50 ppm clock and how soon each is 10 milliseconds out. Compute TAI minus UTC and GPS minus UTC from the 27 leap seconds, and the average number of leap seconds a year from 1972 to 2016. Then apply the NTP round-trip and offset formulas to t0 = 100.000, t1 = 100.550, t2 = 100.551 and t3 = 100.101.

๐Ÿ“„ View solution
Exercise 3

Show noon UTC on 1 July 2027 in London, New York and Tokyo using zoneinfo. Demonstrate with UTC arithmetic the London local time that is skipped in March 2027 and the one that occurs twice in October. Then compute the overflow time of a 32-bit hundredths-of-a-second counter and write a leap-year test that gets 1900, 2000, 2024 and 2100 right.

๐Ÿ“„ View solution

Quick Reference

  • Unix time: seconds since 00:00:00 UTC, 1 January 1970; every day counted as exactly 86,400 seconds
  • 2038 problem: signed 32-bit maximum 2,147,483,647 = 03:14:07 UTC, 19 January 2038; unsigned 32-bit lasts to 7 February 2106; signed 64-bit lasts about 292 billion years
  • UTC: atomic rate, kept within 0.9 s of Earth rotation by leap seconds; first on 30 June 1972, 27 in all, last at the end of 2016; TAI − UTC = 37 s, GPS − UTC = 18 s; leap seconds are due to be dropped by 2035
  • Drift: 1 ppm = 0.0864 s a day; 50 ppm = 4.32 s a day
  • NTP: round trip = (t3 − t0) − (t2 − t1); offset = ((t1 − t0) + (t2 − t3)) / 2; strata 0, 1, 2…
  • Time zones: use named zones from the tz database, never fixed offsets; store UTC and convert for display
  • Bug checklist: small counters (248.55 days, 19.6-year GPS weeks), two-digit years, the leap-year rule, local times at clock changes
Coming next
Time: Clocks, Calendars and How We Measure It 12 is the final chapter. It asks why clocks at different heights disagree, what the satellites correct for, how scientists date rocks millions of years old, and what has been proposed to replace the calendar altogether.