2017-02-17 105 views
1

我有这样的日期格式:蟒蛇时区GMT转换

Sat Apr 14 21:05:23 GMT-00:00 2018 

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

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

什么是GMT的日期/时间格式? document没有GMT。

+0

你指的是什么文件? – AlG

+0

可能的重复http://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python? – AlG

+0

这里是链接到文档:https://docs.python.org/3/library/datetime.html – user1224224

回答

1

处理时区总是有点混乱。在你的例子中,你的需求并不具体,因为它涉及到时区。

固定区偏移:

一读你写的什么样的方式是,在您的字符串时区信息始终是GMT-00:00。如果时区始终是相同的,那么它是一个简单的事情,以建立一个strptime字符串:

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

这使得没有努力解释时区,因为它是固定的。这会给你时区天真datetime。由于您的示例立即将datetime转换为timetuple,我认为这是您想要的结果。

测试:

解读时区偏移:

如果您在您的时间戳非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) 

此功能将占用您的时间字符串并利用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 

时区意识到:

上述代码返回一个UTC相对时区幼稚datetime。它,如果你需要知道datetime一个时区,那么你就可以做到这一点:

datetime.replace(tzinfo=pytz.UTC)) 

测试:

>>> 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 
+0

在我的情况,看起来像我总是有GMT-00:00。非常感谢你的回答。我的问题解决了。 – user1224224