# Time 11, Exercise 1: Unix time, the year 2038 and what 32 bits can hold from datetime import datetime, timedelta, timezone epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) # Part 1: turn some Unix timestamps into dates (always in UTC). for stamp in (0, 86400, 1_000_000_000, 1_700_000_000): when = epoch + timedelta(seconds=stamp) print(stamp, "->", when.strftime("%Y-%m-%d %H:%M:%S"), "UTC") # Part 2: a signed 32-bit number holds at most 2**31 - 1. biggest = 2 ** 31 - 1 print("largest signed 32-bit value:", biggest) last_moment = epoch + timedelta(seconds=biggest) print("last second it can hold:", last_moment.strftime("%Y-%m-%d %H:%M:%S"), "UTC") print("one second later it wraps to:", -2 ** 31, "which is", (epoch + timedelta(seconds=-2 ** 31)).strftime("%Y-%m-%d %H:%M:%S"), "UTC") # Part 3: how long does each size last, counted from 1970? SECONDS_PER_YEAR = 365.2425 * 86400 # average Gregorian year print("signed 32-bit lasts about", round(biggest / SECONDS_PER_YEAR, 1), "years") unsigned = 2 ** 32 - 1 print("unsigned 32-bit lasts about", round(unsigned / SECONDS_PER_YEAR, 1), "years, to", (epoch + timedelta(seconds=unsigned)).strftime("%Y-%m-%d %H:%M:%S"), "UTC") print("signed 64-bit lasts about", f"{(2 ** 63 - 1) / SECONDS_PER_YEAR:.3g}", "years") # Output when run: # 0 -> 1970-01-01 00:00:00 UTC # 86400 -> 1970-01-02 00:00:00 UTC # 1000000000 -> 2001-09-09 01:46:40 UTC # 1700000000 -> 2023-11-14 22:13:20 UTC # largest signed 32-bit value: 2147483647 # last second it can hold: 2038-01-19 03:14:07 UTC # one second later it wraps to: -2147483648 which is 1901-12-13 20:45:52 UTC # signed 32-bit lasts about 68.1 years # unsigned 32-bit lasts about 136.1 years, to 2106-02-07 06:28:15 UTC # signed 64-bit lasts about 2.92e+11 years # Reading the output: a 32-bit signed counter runs out 68 years after 1970, in January 2038, # and wraps round to a date in 1901. Using 64 bits (or an unsigned 32-bit number, which only # postpones the problem to 2106) fixes it. 2.92e+11 is about 292 billion years, far longer # than the universe has existed.