0

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...

4
  • 1
    How are reading the data from what sensor? Commented Sep 7, 2021 at 15:54
  • @Klaus D. via serial (the sensor is USB). Commented Sep 7, 2021 at 17:34
  • You should not expect any helpful answer without providing your code, the sensors specification and the exact data send and received (best in ASCII and HEX). Commented Sep 7, 2021 at 17:58
  • @Klaus D. Sorry, I rephrased the question, it was probably misleading. Communication is no problem, and I know that I have an NTP time. Commented Sep 7, 2021 at 19:22

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

The portion to the right of the '.' place seems incorrect. In the NTP format, it is in units of 1/2^32. Whereas in datetime format, it is in units of 1/1,000,000. So, the numbers should not be same, but they are both 829307.
Value right of decimal is fractional seconds. If want NTP 1/2^32 fraction then can call ntplib._to_frac(ntptime) which is used internally when setting the NTPPacket data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.