我正在尝试比较两个日期值:
1) 2016 年 6 月 23 日 10:36:31 美国东部时间
2) 2016 年 6 月 23 日星期四 07:36:31 GMT
为此,我需要将第二个日期转换为与第一个日期相同的日期格式,因此我使用以下代码:
import datetime
date = datetime.datetime.strptime("Thu, 23 Jun 2016 07:36:31 GMT", "%a, %d %b %Y %H:%M:%S %Z")
.strftime('%b %d, %Y %H:%M:%S %Z')
并得到以下输出:
Jun 23, 2016 07:36:31
这仍然是 GMT
时间(也未指定时区值)
我应该如何更新我的 strftime
参数以获取 Jun 23, 2016 10:36:31 EET
作为输出?
附注EET
是我本地的时区
最佳答案
以下是使用 pytz
模块的基本方法:
import datetime
import pytz
fmt = "%a, %d %b %Y %H:%M:%S %Z"
date = datetime.datetime.strptime("Thu, 23 Jun 2016 07:36:31 GMT", fmt)
gmt_date = pytz.timezone('GMT').localize(date)
print("Time in GMT:", gmt_date.strftime(fmt), sep='\n')
# Now to convert! Notice it took into account "summer time"
print("Time in EET",
gmt_date.astimezone(pytz.timezone('EET')).strftime(fmt), sep='\n')
我的输出:
Time in GMT:
Thu, 23 Jun 2016 07:36:31 GMT
Time in EET
Thu, 23 Jun 2016 10:36:31 EEST
请阅读文档,因为使用时区很棘手,并且有很多注意事项:
关于python - 如何在日期格式中指定时区以获取本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37985892/