You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LoPy4的MicroPython中获取真实日期时间(PySense项目)

在LoPy4上获取真实日期时间的解决方案

你的问题根源在于LoPy4的内置RTC(实时时钟)没有后备电池,每次上电或重启后,RTC会重置到Unix纪元起始时间(1970-01-01),utime.localtime()读取的就是这个未同步的RTC时间。以下是几种可行的解决方法:

1. WiFi网络NTP同步(最常用)

如果你的LoPy4能连接WiFi,直接通过NTP服务器同步时间是最简单的方案。

代码示例:

import network
import utime
import ntptime

# 连接WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("你的WiFi名称", "你的WiFi密码")

# 等待连接成功
while not wlan.isconnected():
    utime.sleep(1)

# 同步NTP时间(默认使用pool.ntp.org)
ntptime.settime()

# 读取并格式化UTC时间
current_time = utime.localtime()
timestamp = "{:04}-{:02}-{:02} {:02}:{:02}:{:02}".format(
    current_time[0], current_time[1], current_time[2],
    current_time[3], current_time[4], current_time[5]
)
print("UTC Timestamp: {}".format(timestamp))

# 转换为本地时区(以东八区为例,增加8小时)
local_time = utime.localtime(utime.mktime(current_time) + 8*3600)
local_timestamp = "{:04}-{:02}-{:02} {:02}:{:02}:{:02}".format(
    local_time[0], local_time[1], local_time[2],
    local_time[3], local_time[4], local_time[5]
)
print("Local Timestamp: {}".format(local_timestamp))

2. LoRaWAN时间同步(若使用LoRa网络)

如果你的LoPy4通过LoRaWAN连接网络,可以利用LoRaWAN的MAC命令从网络服务器获取时间。

代码示例(基于Pycom的LoRa库):

from network import LoRa
import utime

# 初始化LoRaWAN,根据你的地区调整区域参数
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)

# 此处补充你的LoRaWAN OTAA/ABP连接配置
# ... 例如设置dev_eui、app_eui、app_key等 ...

# 等待网络连接完成
while not lora.has_joined():
    utime.sleep(2)

# 请求网络时间同步
lora.request_time()

# 等待时间同步完成
while not lora.time_sync():
    utime.sleep(1)

# 获取并格式化时间
current_time = utime.localtime()
timestamp = "{:04}-{:02}-{:02} {:02}:{:02}:{:02}".format(
    current_time[0], current_time[1], current_time[2],
    current_time[3], current_time[4], current_time[5]
)
print("LoRaWAN Timestamp: {}".format(timestamp))

3. 手动设置时间(临时测试用)

如果没有网络,可以手动设置RTC时间,重启后会失效。

代码示例:

import utime

# 定义目标时间元组:(年, 月, 日, 时, 分, 秒, 星期, 年内天数)
target_time = (2024, 5, 20, 14, 30, 0, 0, 0)

# 转换为时间戳并设置RTC
utime.settime(utime.mktime(target_time))

# 验证时间
current_time = utime.localtime()
timestamp = "{:04}-{:02}-{:02} {:02}:{:02}:{:02}".format(
    current_time[0], current_time[1], current_time[2],
    current_time[3], current_time[4], current_time[5]
)
print("Manual Timestamp: {}".format(timestamp))

内容的提问来源于stack exchange,提问作者Pedro Almeida

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:42:56