Search code examples
pythondatetimetimedigitsntp

How to extract seconds from time taken from ntp server


I was able to get the current time from an NTP server with the following code. Now I tried to get the seconds from the time but it did not work. Can someone please explain how I can take the seconds only from the time.

I tried to convert the time into a list with integers in it and then take the 18th and 19th digit.

import ntplib
from datetime import datetime, timezone
c = ntplib.NTPClient()
        # Provide the respective ntp server ip in below function
response = c.request('uk.pool.ntp.org', version=3)
response.offset
        # UTC timezone used here, for working with different timezones you can use [pytz library][1]
currenttime =datetime.fromtimestamp(response.tx_time, timezone.utc)
print (currenttime)
d = map(int, str(currenttime))
print (list(d))

This is what I got on the console.

2019-07-15 20:56:19.952231+00:00

ValueError: invalid literal for int() with base 10: '-'

Solution

  • Extract the seconds from the datetime object you've already created:

    d = currenttime.second
    

    See also: datetime.second - Python documentation