首页 > 解决方案 > Micropython获取正确的当前时间

问题描述

因为 micropython 不导入日期时间。

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

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

我想时间从2000/1/1.

如何设置开始时间?

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

谢谢!

标签: pythonmicropython

解决方案


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

import ntptime
import time

#if needed, overwrite default time server
ntptime.host = "1.europe.pool.ntp.org"

try:
  print("Local time before synchronization:%s" %str(time.localtime()))
  #make sure to have internet connection
  ntptime.settime()
  print("Local time after synchronization:%s" %str(time.localtime()))
except:
  print("Error syncing time")

推荐阅读