站长
发布于 2023-10-27 / 126 阅读 / 0 评论 / 0 点赞

MicroPython 同步网络时间

import utime,ntptime
# 同步时间
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800 # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com' # 可选,ntp服务器,默认是"pool.ntp.org"   
     try:
         ntptime.settime() # 修改设备时间
         print("同步后本地时间:%s" %str(utime.localtime()))
     except Exception as e:
         print('同步失败')
         print("Error:", e)

踩坑:

  • 需要配置偏移时间,默认是UTC0,国内是+8

  • 默认时间服务器是在国外,网络较差,容易出现同步失败情况,配置一个国内的服务器地址

  • 需要考虑同步失败时报错的异常处理