ntptime.py 850 B

1234567891011121314151617181920212223242526272829303132333435
  1. try:
  2. import usocket as socket
  3. except:
  4. import socket
  5. try:
  6. import ustruct as struct
  7. except:
  8. import struct
  9. # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
  10. NTP_DELTA = 3155673600
  11. host = "pool.ntp.org"
  12. def time():
  13. NTP_QUERY = bytearray(48)
  14. NTP_QUERY[0] = 0x1b
  15. addr = socket.getaddrinfo(host, 123)[0][-1]
  16. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  17. s.settimeout(1)
  18. res = s.sendto(NTP_QUERY, addr)
  19. msg = s.recv(48)
  20. s.close()
  21. val = struct.unpack("!I", msg[40:44])[0]
  22. return val - NTP_DELTA
  23. # There's currently no timezone support in MicroPython, so
  24. # utime.localtime() will return UTC time (as if it was .gmtime())
  25. def settime():
  26. t = time()
  27. import machine
  28. import utime
  29. tm = utime.localtime(t)
  30. tm = tm[0:3] + (0,) + tm[3:6] + (0,)
  31. machine.RTC().datetime(tm)