Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Micropython get correct current time

Because of micropython doesn't import the datetime.

I want use time or utime modules to get current time.

But the time.localtime() result is like (2000, 1, 1, 0, 12, 35, 5, 1)

I guess the time start at the 2000/1/1.

How to set the start time on that?

Or other recommanded way can do the correct result?

Thanks!

like image 321
Hsinhsin Hung Avatar asked May 09 '26 11:05

Hsinhsin Hung


2 Answers

You can use a library to set time via internet over NTP protocol. You have to be connected with the internet for example wifi on esp32

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")
like image 153
emch2 Avatar answered May 11 '26 00:05

emch2


Use RTC to set the time:

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

You can then just use time.localtime() and string formatting to make it look however you want.

like image 27
John S Avatar answered May 11 '26 01:05

John S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!