使用python转换从ntp服务器检索的日期 [英] Convert date retrieved from ntp server with python

查看:185
本文介绍了使用python转换从ntp服务器检索的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to convert time retrieved from NTP server (with python script) in this format "Wed Jul 13 00:17:58 CEST 2011" to this format "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

I get this format : "Wed Jul 13 00:17:58 CEST 2011"

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

I want to convert this into this format "2011-07-13 00:17:58" ( '%Y-%m-%d %H:%M:%S' )

感谢:)

推荐答案

在你的情况下,你可以直接从秒数到你想要的时间格式然而,我将在底部的案例的确切代码段之前解释一般解决方案。

In your case you can go directly from the number of seconds to the time format you desire; however I will explain the general solution before the exact snippet for your case at the bottom.

一般来说,这种类型的问题是通过 strptime strftime 。您还应参考python文档中的格式代码

In general this type of problem is solved with the help of strptime and strftime. You should also refer to the formatting codes in the python docs.

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

strptime() matches the pieces of a date string and creates a python time structure. strftime() can then be used to convert that time structure into whatever format you desire.

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")

或在您的具体情况可以替换

Or in your particular case, you can replace

utc_secs = time.ctime(utc_secs)

with(注意:如果您还没有从datetime import datetime 中完成,那么您应该使用 datetime.datetime.fromtimestamp 下面,而不是简单的 datetime.fromtimestamp

with (NOTE: if you have not done from datetime import datetime then you should use datetime.datetime.fromtimestamp below and not simply datetime.fromtimestamp)

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

这篇关于使用python转换从ntp服务器检索的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆