Converting NTP timestamp to datetime in Python

In Python, I have a 64bit floating point number representing a NTP time. I like to convert that in a readable format, e.g. a datetime object.

According to wikipedia the first 32 bit contain the time since 1970, and the last 32 bit are fractions of seconds, which I’m not interested in. However, as I have a float, not an int, how can I access the first 32 bit only? Bitshift doesn’t work…

Answer

The ntplib python module has functions to convert from datetime timestamp to NTP timestamp and back.

import ntplib
from datetime import datetime, timezone

dt = datetime.now(timezone.utc).timestamp()
print("timestamp:", dt)

# convert datetime to NTP time
ntptime = ntplib.system_to_ntp_time(dt)
print("NTP time: ", ntptime)

# convert NTP time to datetime timestamp
ts = ntplib.ntp_to_system_time(ntptime)
print("timestamp:", ts)

# convert system timestamp to datetime
print("datetime:", datetime.fromtimestamp(ts))

# convert 1-Jan-1970 epoch datetime to NTP time
ntptime = ntplib.system_to_ntp_time(0)
print("nNTP time: ", ntptime)
ts = ntplib.ntp_to_system_time(ntptime)
print("datetime:", datetime.fromtimestamp(ts, tz=timezone.utc))

Output:

timestamp: 1631063844.829307
NTP time:  3840052644.829307
timestamp: 1631063844.829307
datetime:  2021-09-08 01:17:24.829307+00:00

NTP time:  2208988800
datetime: 1970-01-01 00:00:00+00:00