micropython / micropython-lib

Core Python libraries ported to MicroPython
Other
2.3k stars 980 forks source link

ntptime: Year 2036 fix. #837

Closed jonfoster closed 1 month ago

jonfoster commented 3 months ago

Fix a bug in the NTP client, where it would report the wrong time after 7 Feb 2036.

The NTP timestamp has a 32-bit count of seconds, which will wrap back to zero on 7 Feb 2036 at 06:28:16.

It's now March 2024. So we know that timestamps less than 1st Jan 2024 are impossible. So if the timestamp appears to be earlier than 1st Jan 2024, that probably means that the NTP time wrapped at 2^32 seconds. (Or someone set the wrong time on their NTP server, but we can't really do anything about that). So in that case, we need to add in those extra 2^32 seconds, to get the correct timestamp.

This means that this code will work until the year 2160.

(More precisely, this code will not work after 7th Feb 2160 at 06:28:15. Fixing that is someone else's problem, some time in the far future, by adjusting the NTP_DELTA and MIN_NTP_TIMESTAMP values. By just changing those two numbers, you can choose any 136-year span of time that will be supported).

This replaces https://github.com/micropython/micropython-lib/pull/830 because apparently in GitHub, once I've made a Pull Request I can't change what branch it's pulling from, and I accidentally set up 830 to pull from my "master" branch.

projectgus commented 3 months ago

Nice fix, @jonfoster . I wasn't familiar with this issue, but these articles gave me a pretty good background for anyone else who is curious: https://www.eecis.udel.edu/~mills/time.html