【问题标题】:How to extract seconds from time taken from ntp server如何从 ntp 服务器获取的时间中提取秒数
【发布时间】: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


【解决方案1】:

从您已经创建的datetime 对象中提取秒数:

d = currenttime.second

另请参阅:datetime.second - Python documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多