Reputation: 7691
I need to generate a timestamp in NTP format in Python. Specifically, I need to calculate the number of seconds since 1st January 1900, as a 32-bit number. (NTP timestamps are actually 64 bits, with the other 32 bits representing fractions of seconds - I'm not worried about this part).
How should I go about doing this?
Upvotes: 3
Views: 10762
Reputation: 23303
import datetime
diff = datetime.datetime.utcnow() - datetime.datetime(1900, 1, 1, 0, 0, 0)
timestamp = diff.days*24*60*60+diff.seconds
timestamp
# returns
# 3531049334
(note that timedelta.total_seconds()
is not available in python3)
Upvotes: 3
Reputation: 363807
from datetime import datetime
(datetime.utcnow() - datetime(1900, 1, 1)).total_seconds()
That returns a float
which you can truncate in the obvious way. Be sure to put in a check that the result is <= 2**32-1
, since your program is bound to break in 2036.
Upvotes: 1
Reputation: 80831
From the python ntplib :
SYSTEM_EPOCH = datetime.date(*time.gmtime(0)[0:3])
NTP_EPOCH = datetime.date(1900, 1, 1)
NTP_DELTA = (SYSTEM_EPOCH - NTP_EPOCH).days * 24 * 3600
def ntp_to_system_time(date):
"""convert a NTP time to system time"""
return date - NTP_DELTA
def system_to_ntp_time(date):
"""convert a system time to a NTP time"""
return date + NTP_DELTA
and this is used like this :
ntp_time = system_to_ntp_time(time.time())
Upvotes: 3
Reputation: 4348
You should take a look at ntplib
, which is available via PyPi:
http://pypi.python.org/pypi/ntplib/
Upvotes: 2