3

When running on batteries the Pico W's clock/utime starts at 2021-01-01 00:00:00 by default.

At every boot it obviously should:

  • Get the current time on its own, likely off the internet.
  • Set it's internal chips to that time so that its utime library gives back the correct time going forward.

Any good established technique out there to achieve this?

Using micropython.

Flood
  • 345
  • 7
  • 12

1 Answers1

5

You can use the ntptime module available from the micropython library. Once that's installed, using it is simple:

>>> import time
>>> import ntptime
>>> time.localtime()
(2000, 1, 1, 0, 0, 57, 5, 1)
>>> ntptime.settime()
>>> time.localtime()
(2022, 7, 21, 1, 49, 1, 3, 202)

Put something like this in your main.py and you should be all set.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • 1
    Worked well after I adjusted NTP_DELTA to 2209075200 - 71999 if I care to be off by roughly +0.5 seconds; or 72000 if by -0.5 seconds, probably due to internals of the host, network and Pico. It wants an Integer so I had to pick one. It's good enough for this project. Also looks like it'll keep the correct time so long as the Pico is in my time zone. Incorporating time zone logic is going to be a challenge for another project. Thank you. – Flood Jul 21 '22 at 03:24
  • The link is dead. Did you mean [this](https://github.com/micropython/micropython-lib/tree/master/micropython)? – normanius Mar 27 '23 at 00:03
  • The link (now updated) was specifically to the `ntptime` module, so [this](https://github.com/micropython/micropython-lib/blob/master/micropython/net/ntptime/ntptime.py). – larsks Mar 27 '23 at 01:52