如何在Python中找到不同时区的时间之间的差异? [英] How do I find difference between times in different timezones in Python?

查看:151
本文介绍了如何在Python中找到不同时区的时间之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算格式如下的两个日期/时间之间的差异(以秒为单位):

I am trying to calculate difference(in seconds) between two date/times formatted as following:

2010-05-11 17:07:33 UTC

2010-05-11 17:07:33 UTC

2010-05-11 17:07:33 EDT

2010-05-11 17:07:33 EDT

time1 = '2010-05-11 17:07:33 UTC'
time2 = '2010-05-11 17:07:33 EDT'
delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\
        time.mktime(time.strptime(time2, "%Y-%m-%d %H:%M:%S %Z"))

我得到的问题是EDT无法识别,具体错误是

The problem I got is EDT is not recognized, the specific error is

ValueError: time data '2010-05-11 17:07:33 EDT' does not match format '%Y-%m-%d %H:%M:%S %Z'


推荐答案

查看 pytz 世界时区定义库。

Check out the pytz world timezone definitions library.


该库允许使用Python 2.3或更高版本进行准确的跨平台时区计算。它还解决了夏令时结束时时间模糊的问题,您可以在Python库参考(datetime.tzinfo)中了解更多信息。

This library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library Reference (datetime.tzinfo).

它利用 tz数据库 的优势应该包括EDT,并允许您执行所需的计算(并且可能比当前的实现更可靠,更准确)。

It takes advantage of the tz database, which should include EDT, and allow you to perform the calculations you need to (and probably more reliably & accurately than your current implementation).

这篇关于如何在Python中找到不同时区的时间之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆