由于micropython没有导入datetime模块,我想使用time或utime模块获取当前时间。但是,time.localtime()返回的结果类似于(2000, 1, 1, 0, 12, 35, 5, 1)。我猜时间从2000/1/1开始计算。如何在此基础上设置起始时间?或者有其他推荐的方式可以得到正确的结果吗?谢谢!
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")
time-a-g.nist.gov
。你可以通过执行 time.localtime(time.time() + (-4 * 3600))
来调整本地时间的UTC。 - undefined使用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()
和字符串格式化,以便将其呈现为你想要的样子。mpremote
。mpremote
是一个MicroPython实用程序,您可以将其安装到PC上,并使用其中的命令将MCU时间设置为PC时间。要求是MCU通过串行连接(并且同时没有其他东西使用该端口)。安装 mpremote: pip install -U mpremote
。PS C:\develop\MyPython\> mpremote setrtc repl
Connected to MicroPython at COM14
Use Ctrl-] to exit this shell
>
MicroPython v1.19.1 on 2022-06-18; ESP32S3 module with ESP32S3
Type "help()" for more information.
>>> import time
>>> time.localtime()
(2020, 1, 1, 10, 0, 17, 2, 1)
在这里,mpremote
会自动检测第一个设备,连接到该设备,设置时间,并进入MicroPython repl。
更多信息请参见:https://docs.micropython.org/en/latest/reference/mpremote.html
使用utime函数可以获取本地时间,如下所示。
#Get the current time
current_time = utime.localtime()
#Format the current time as "dd/mm/yyyy HH:MM"
formatted_time = "{:02d}/{:02d}/{} {:02d}:{:02d}".format(current_time[2], current_time[1], current_time[0], current_time[3], current_time[4])
tm_year: the current year (e.g. 2022)
tm_mon: the current month (1-12)
tm_mday: the current day of the month (1-31)
tm_hour: the current hour (0-23)
tm_min: the current minute (0-59)
tm_sec: the current second (0-59)
tm_wday: the current day of the week (0-6, Monday is 0)
tm_yday: the current day of the year (1-366)
tm_isdst: 1 if Daylight Saving Time is in effect, 0 otherwise.