-2

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: '-'
EOFF
  • 83
  • 1
  • 8
  • Please [read the docs](https://docs.python.org/3.7/library/datetime.html?highlight=datetime#datetime.datetime.second) about accessing elements of `datetime.datetime` objects. As a sidenote: what's the point of converting a timestamp to a _data structure_ representing date & time if you're then converting this _structure_ to an _unstructured_ string? – ForceBru Jul 15 '19 at 21:07
  • ... why not just retrieve it with [`datetime.second`](https://docs.python.org/2/library/datetime.html#datetime.datetime.second)? – esqew Jul 15 '19 at 21:08
  • Thanks guys! I just watched a short tutorial video about datetime object. Now I will read the docs to get a better understanding. – EOFF Jul 15 '19 at 21:29

1 Answers1

1

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

d = currenttime.second

See also: datetime.second - Python documentation

esqew
  • 42,425
  • 27
  • 92
  • 132