Micropython 获取正确的当前时间

Hsi*_*ung 8 python micropython

因为 micropython 不导入日期时间。

我想使用 time 或 utime 模块来获取当前时间。

但 time.localtime() 结果就像(2000, 1, 1, 0, 12, 35, 5, 1)

我猜时间是从 开始的2000/1/1

如何设置开始时间?

或者其他推荐的方法可以得到正确的结果?

谢谢!

小智 16

您可以使用库通过 NTP 协议通过互联网设置时间。您必须连接到互联网,例如 esp32 上的 wifi

\n
import ntptime\nimport time\n\n#if needed, overwrite default time server\nntptime.host = "1.europe.pool.ntp.org"\n\ntry:\n  print("Local time before synchronization\xef\xbc\x9a%s" %str(time.localtime()))\n  #make sure to have internet connection\n  ntptime.settime()\n  print("Local time after synchronization\xef\xbc\x9a%s" %str(time.localtime()))\nexcept:\n  print("Error syncing time")\n
Run Code Online (Sandbox Code Playgroud)\n


Joh*_*n S 3

使用RTC设置时间:

from pyb import RTC   # or import from machine depending on your micropython version
rtc = RTC()
rtc.datetime((2019, 5, 1, 4, 13, 0, 0, 0))
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用time.localtime()字符串格式来使其看起来像您想要的那样。

  • 您可以使用 RTC 对象手动设置它。你是说你想把它从互联网上关闭吗?如果是这样,那么您将需要使用 NTP 服务器。如何执行此操作可能取决于您正在使用的 Micropython 端口。寻找ntptime。 (2认同)