###from: https://github.com/micropython/micropython-lib/blob/master/micropython/net/ntptime/ntptime.py
#libraries
import machine, network
try:
import utime as time
except:
import time
try:
import usocket as socket
except:
import socket
try:
import ustruct as struct
except:
import struct
#change according to your system (board)
UNIX_OFFSET = 946684800
NTP_OFFSET = 3155673600
def getNtpTime(host = "pool.ntp.org", timeout = 3):
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1B
addr = socket.getaddrinfo(host, 123)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.settimeout(timeout)
res = s.sendto(NTP_QUERY, addr)
msg = s.recv(48)
finally:
s.close()
val = struct.unpack("!I", msg[40:44])[0]
return val - NTP_OFFSET
def connectWiFi():
print("Connecting to WiFi")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".")
time.sleep(1)
print("Connected!")
connectWiFi()
time.sleep(5);
print(getNtpTime())