【发布时间】:2019-07-15 21:04:01
【问题描述】:
我能够使用以下代码从 NTP 服务器获取当前时间。现在我试图从时间中获取秒数,但它没有用。有人可以解释一下我如何只从时间中获取秒数。
我尝试将时间转换为一个包含整数的列表,然后取第 18 位和第 19 位。
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))
这是我在控制台上得到的。
2019-07-15 20:56:19.952231+00:00
ValueError: invalid literal for int() with base 10: '-'
【问题讨论】:
-
请read the docs 访问
datetime.datetime对象的元素。作为旁注:如果您将此 structure 转换为 unstructured,那么将时间戳转换为表示日期和时间的 data structure 有什么意义? > 字符串? -
...为什么不直接用
datetime.second检索它? -
谢谢大家!我刚刚观看了有关 datetime 对象的简短教程视频。现在我将阅读文档以获得更好的理解。
标签: python datetime time digits ntp