MicroPython获取正确的当前时间

8
由于micropython没有导入datetime模块,我想使用time或utime模块获取当前时间。但是,time.localtime()返回的结果类似于(2000, 1, 1, 0, 12, 35, 5, 1)。我猜时间从2000/1/1开始计算。如何在此基础上设置起始时间?或者有其他推荐的方式可以得到正确的结果吗?谢谢!

1
谷歌为我带来了这个主题 - Sangbok Lee
@Sangbok Lee 感谢您的回复。但是RTC类也会返回2000/1/1,可能需要手动设置时间。 - Hsinhsin Hung
4个回答

15
您可以使用一个库通过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")

我使用 time-a-g.nist.gov。你可以通过执行 time.localtime(time.time() + (-4 * 3600)) 来调整本地时间的UTC。 - undefined

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))

你可以使用time.localtime()和字符串格式化,以便将其呈现为你想要的样子。

1
但是我该如何获得(2019,5,1,4,13,0,0,0)这个时间?因为当板子连接时,使用这些方法总是得到2000/1/1。 - Hsinhsin Hung
2
您可以使用RTC对象手动设置时间。如果您想从互联网上设置时间,那么您需要使用NTP服务器。如何做可能取决于您使用的Micropython端口。请查找ntptime。 - John S
如果您的板子具备该功能,另一种获取时间的方法是从GPS数据中获取。 - Patrick
这个问题是关于获取当前时间而不是设置它。 - Saeed
这个问题是关于获取当前时间而不是设置它。 - undefined

1
如果您的问题是:如何在没有网络连接的情况下设置板子的时间,最简单的方法(现在)是使用 mpremotempremote 是一个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


0

使用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])

这段代码使用 localtime() 函数获取当前时间,然后使用字符串格式化将时间格式化为所需的格式。它使用 struct_time 对象的 tm_mday、tm_mon、tm_year、tm_hour 和 tm_min 属性创建格式化字符串。:02d 用于将值格式化为 2 位数字,这确保单个数字的日期和月份会以前导零填充。
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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接