3

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?

4 Answers 4

3
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)

Sign up to request clarification or add additional context in comments.

1 Comment

Just to note - timedelta.total_seconds() is available under Python 2.7 and Python >= 3.2, it's just the earlier 2.x, 3.0 and 3.1 releases that lacked it.
3

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())

Comments

2

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

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

Comments

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

Comments

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.