thomson_matt
thomson_matt

Reputation: 7691

NTP timestamps in Python

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

Answers (4)

Adrien Plisson
Adrien Plisson

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

Fred Foo
Fred Foo

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

C&#233;dric Julien
C&#233;dric Julien

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

Fabian
Fabian

Reputation: 4348

You should take a look at ntplib, which is available via PyPi:

http://pypi.python.org/pypi/ntplib/

Upvotes: 2

Related Questions