1
A
回答
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
相关问题
- 1. 获取GMT时间蟒蛇
- 2. 蟒蛇转换
- 3. GMT时区转换在目标c
- 4. 将NSDate转换为GMT时区
- 5. 转换蟒蛇时间戳年
- 6. 蟒蛇到PHP转换
- 7. 蟒蛇拉丁转换器
- 8. 日期转换蟒蛇
- 9. 转换阵列蟒蛇标
- 10. 自动转换到蟒蛇
- 11. 转换Excel以CSV蟒蛇
- 12. 转换CSV与蟒蛇
- 13. 从JSON转换由蟒蛇
- 14. 转换蟒蛇名单pd.DataFrame
- 15. 蟒蛇生成器转换
- 16. 蟒蛇ASCII到Unicode转换
- 17. 转换蟒蛇struct.pack到C#
- 18. Java来蟒蛇转换
- 19. 蟒蛇转换STR列出
- 20. 转换输出到蟒蛇
- 21. 蟒蛇C转换误差
- 22. 蟒蛇字符集转换
- 23. 蟒蛇EXE转换代码
- 24. 蟒蛇 - XML到CSV转换
- 25. 将GMT时区转换为用户特定时区
- 26. 在numpy的(蟒蛇)转换时间字符串转换为datetime
- 27. GMT-0400和GMT-0500转换
- 28. 转换本地时间GMT
- 29. 换取蟒蛇
- 30. 以GMT格式转换为当前时区的时间
你指的是什么文件? – AlG
可能的重复http://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python? – AlG
这里是链接到文档:https://docs.python.org/3/library/datetime.html – user1224224