【问题标题】:Convert date retrieved from ntp server with python使用python转换从ntp服务器检索的日期
【发布时间】:2011-10-04 01:22:07
【问题描述】:

是否可以将以这种格式“Wed Jul 13 00:17:58 CEST 2011”从 NTP 服务器(使用 python 脚本)检索到的时间转换为这种格式“2011-07-13 00:18:10”

    client = socket(AF_INET, SOCK_DGRAM)
    data = '\x1b' + 47 * '\0'
    client.sendto(data, (ntp.server.com,123))
    data, address = client.recvfrom( 1024 )
    if data:
        utc_secs = struct.unpack('!12I', data)[10]
        utc_secs -= 2208988800L
        utc_secs = time.ctime(utc_secs)
        print utc_secs
        return utc_secs

我得到这种格式:“Wed Jul 13 00:17:58 CEST 2011”

我想把它转换成这种格式 "2011-07-13 00:17:58" ('%Y-%m-%d %H:%M:%S')

谢谢:)

【问题讨论】:

    标签: python date format ntp


    【解决方案1】:

    在您的情况下,您可以直接从秒数转到您想要的时间格式;但是,我将在底部针对您的案例的确切 sn-p 之前解释一般解决方案。

    一般来说,这类问题是在strptimestrftime 的帮助下解决的。您还应该参考 python 文档中的formatting codes

    strptime() 匹配日期字符串的片段并创建 python 时间结构。然后可以使用strftime() 将该时间结构转换为您想要的任何格式。

    from datetime import datetime
    ntp_time = datetime.strptime(time_str_from_ntp, "%a %b %y %H:%M:%S")
    formatted_time = datetime.strftime(ntp_time, "%Y-%m-%d %H:%M:%S")
    

    或者在您的特定情况下,您可以替换

    utc_secs = time.ctime(utc_secs)
    

    with(注意:如果您还没有使用from datetime import datetime,那么您应该使用下面的datetime.datetime.fromtimestamp 而不仅仅是datetime.fromtimestamp

    formatted_time = datetime.fromtimestamp(utc_secs).strftime("%Y-%m-%d %H:%M:%S")
    

    【讨论】:

    • 我不知道这在 2011 年是否正确,但我认为第一个代码块中 ntp_time = ... 的行应该更正为ntp_time = datetime.strptime(time_str_from_ntp, "%a %b %d %H:%M:%S %Y")
    【解决方案2】:
    >>> sec #your utc_secs
    1310511730
    >>> time.ctime(sec) #instead of this
    'Wed Jul 13 02:02:10 2011'
    >>> d = datetime.datetime.fromtimestamp(sec) #do this
    >>> d   
    datetime.datetime(2011, 7, 13, 2, 2, 10)
    >>> d.strftime('%Y-%m-%d %H:%M:%S')
    '2011-07-13 02:02:10'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      相关资源
      最近更新 更多