Advertisement
DeaD_EyE

compact ntpdate copied from micropython

May 4th, 2022 (edited)
937
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.65 KB | None | 0 0
  1. from datetime import datetime, timedelta, timezone
  2. from socket import socket, getaddrinfo, AF_INET, SOCK_DGRAM
  3. from struct import unpack
  4.  
  5.  
  6. def ntp_date(host="pool.ntp.org"):
  7.     NTP_QUERY = bytearray(48)
  8.     NTP_QUERY[0] = 0x1B
  9.     addr = getaddrinfo(host, 123)[0][-1]
  10.  
  11.     with socket(AF_INET, SOCK_DGRAM) as sock:
  12.         sock.settimeout(1)
  13.         res = sock.sendto(NTP_QUERY, addr)
  14.         try:
  15.             msg = sock.recv(48)
  16.         except TimeoutError:
  17.             return None
  18.        
  19.     date = unpack("!I", msg[40:44])[0]
  20.     # NTPs EPOCH starts at 1900-01-01
  21.     return datetime(1900, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=date)
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement