I found some Python code that gets the current time from NTP servers. It works great with CPython.
I want to convert this to work with Micropython, but there seem to be some issues with the socket library that I can not do anything with. The code is included below and the error message I am getting is at the end. It seems like this should work but Micropython seems to be missing some functionality or there is an alternate way to do this that I am not aware of. I am very new to working with this kind of code.
Code: Select all
from socket import AF_INET, SOCK_DGRAM
import socket
import struct
import time
def getNTPTimeMP(host = "pool.ntp.org"):
port = 123
buf = 1024
address = (host, port)
msg = '\x1b' + 47 * '\0'
# Reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800 # 1970-01-01 00:00:00
# Connect to server
client = socket.socket(AF_INET, SOCK_DGRAM)
client.sendto(msg.encode('utf-8'), address)
msg, address = client.recvfrom( buf )
t = struct.unpack( "!12I", msg )[10]
t -= TIME1970
t1 = time.ctime(t)
time_string = t1.replace(" "," ")
#print("t1 = '{0}',\nt2 = '{1}',\ntime_string = {2}".format(t1, t2, time_string))
return time_string
t = getNTPTimeMP()
z = t.split(" ")
print(t)
print(z)
# MPY: soft reboot
# Traceback (most recent call last):
# File "main.py", line 31, in <module>
# File "main.py", line 19, in getNTPTimeMP
# ValueError: invalid arguments
# MicroPython v1.16 on 2021-06-23; TinyPICO with ESP32-PICO-D4
8-Dale