python时区格林威治标准时间转换

Car*_*eng 3 python timezone datetime

我有这个日期格式:

Sat Apr 14 21:05:23 GMT-00:00 2018
Run Code Online (Sandbox Code Playgroud)

我想用来datetime存储这些数据。

datetime.datetime.strptime(dateString, '%a %b %d %H:%M:%S %Z %Y').timetuple()

GMT 的日期/时间格式是什么?该文件没有格林威治标准时间。

Ste*_*uch 5

处理时区总是有点令人困惑。在您的示例中,您的需求并不具体,因为它与时区有关。

固定时区偏移:

阅读您所写内容的一种方法是您的字符串中的时区信息始终为GMT-00:00. 如果时区始终相同,那么构建一个strptime字符串是一件简单的事情:

dt.datetime.strptime(date, '%a %b %d %H:%M:%S GMT-00:00 %Y')
Run Code Online (Sandbox Code Playgroud)

这不需要解释时区,因为它是固定的。这会给你时区天真datetime。由于您的示例立即将 the 转换datetime为 a timetuple,因此我认为这是您想要的结果。

去测试:

>>> date = "Sat Apr 14 21:05:23 GMT-00:00 2018"
>>> print(dt.datetime.strptime(date, '%a %b %d %H:%M:%S GMT-00:00 %Y'))
2018-04-14 21:05:23
Run Code Online (Sandbox Code Playgroud)

解释时区偏移:

如果您的时间戳中有非 GMT 时区,并且想要保留信息,您可以执行以下操作:

def convert_to_datetime(datetime_string):
    # split on spaces
    ts = datetime_string.split()

    # remove the timezone
    tz = ts.pop(4)

    # parse the timezone to minutes and seconds
    tz_offset = int(tz[-6] + str(int(tz[-5:-3]) * 60 + int(tz[-2:])))

    # return a datetime that is offset
    return dt.datetime.strptime(' '.join(ts), '%a %b %d %H:%M:%S %Y') - \
        dt.timedelta(minutes=tz_offset)
Run Code Online (Sandbox Code Playgroud)

此函数将占用您的时间字符串并使用UTC偏移量。(例如。-00:00)。它将解析字符串中的时区信息,然后将生成的分钟和秒添加回datetime以使其UTC相对。

去测试:

>>> print(convert_to_datetime("Sat Apr 14 21:05:23 GMT-00:00 2018"))
2018-04-14 21:05:23

>>> print(convert_to_datetime("Sat Apr 14 21:05:23 PST-08:00 2018"))
2018-04-15 05:05:23
Run Code Online (Sandbox Code Playgroud)

时区意识:

上面的代码返回一个UTC相对时区 naive datetime。如果您需要时区感知datetime,那么您可以这样做:

datetime.replace(tzinfo=pytz.UTC))
Run Code Online (Sandbox Code Playgroud)

去测试:

>>> import pytz
>>> print(convert_to_datetime("Sat Apr 14 21:05:23 GMT-00:00 2018").replace(tzinfo=pytz.UTC))
2018-04-14 21:05:23+00:00
Run Code Online (Sandbox Code Playgroud)