Micropython获取正确的当前时间
Micropython get correct current time
因为 micropython 不导入日期时间。
我想使用 time 或 utime 模块来获取当前时间。
但是 time.localtime() 结果是
喜欢 (2000, 1, 1, 0, 12, 35, 5, 1)
我猜时间从 2000/1/1
开始。
如何设置开始时间?
或者其他推荐的方式可以得到正确的结果?
谢谢!
使用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))
然后您可以只使用 time.localtime()
和字符串格式来使其看起来像您想要的那样。
您可以使用库通过 NTP 协议通过互联网设置时间。您必须连接到互联网,例如 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")
因为 micropython 不导入日期时间。
我想使用 time 或 utime 模块来获取当前时间。
但是 time.localtime() 结果是
喜欢 (2000, 1, 1, 0, 12, 35, 5, 1)
我猜时间从 2000/1/1
开始。
如何设置开始时间?
或者其他推荐的方式可以得到正确的结果?
谢谢!
使用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))
然后您可以只使用 time.localtime()
和字符串格式来使其看起来像您想要的那样。
您可以使用库通过 NTP 协议通过互联网设置时间。您必须连接到互联网,例如 esp32
上的 wifiimport 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")