python - 如何在日期格式中指定时区以获取本地时间

标签 python python-2.7 date python-3.x datetime

我正在尝试比较两个日期值:

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

请阅读文档,因为使用时区很棘手,并且有很多注意事项:

http://pytz.sourceforge.net/

关于python - 如何在日期格式中指定时区以获取本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37985892/

相关文章:

javascript - 如何在 qweb 报告中添加分隔符?

python - 类型错误 : Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a'

python 如何在不从列表中删除元素的情况下按出现次数对列表进行排序?

python - 检查python列表中的所有项目是否包含子字符串

python - Selenium Python - Webscraping Xpath 错误

ORACLE 不保存日期时间。为什么?

JavaScript Date() 返回无效日期

php - Carbon::now() - 只有一个月

python - 如何创建二十一点游戏作为两个玩家之间的模拟?

python - 如何在 Windows 上静默卸载 Python 2.7?