Skip to content

Instantly share code, notes, and snippets.

@tranch
Last active November 28, 2018 12:43
Show Gist options
  • Save tranch/9278259fdef3a91952b9b1d9cc270b58 to your computer and use it in GitHub Desktop.
Save tranch/9278259fdef3a91952b9b1d9cc270b58 to your computer and use it in GitHub Desktop.
NTP time update for micropython
import socket
import ustruct
import time
from machine import RTC
# datetime.date(2000, 1, 1) - datetime.date(1900, 1, 1)
NTP_DELTA = 3155673600
NTP_SERVER = '0.cn.pool.ntp.org'
def get_ntp_time():
data = bytearray(48)
data[0] = 0x1B
val = 0
addr = socket.getaddrinfo(NTP_SERVER, 123)[0][-1]
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(data, addr)
data, addr = sock.recvfrom(2048)
val = ustruct.unpack("!12I", data)[10]
return val - NTP_DELTA
def sync():
ts = get_ntp_time()
tm = time.localtime(ts)
rtc = RTC()
rtc.datetime(tm[0:3] + (0,) + tm[3:6] + (0,))
if __name__ == '__main__':
sync()
print("Current time:", time.localtime())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment