【问题标题】:Time conversion using pytz isn't accurate [duplicate]使用 pytz 的时间转换不准确 [重复]
【发布时间】:2014-06-23 05:09:13
【问题描述】:

我正在使用pytz'2014.2' 版本。我正在使用以下过程将Asia/Kuwait 时区(即本地时间)转换为UTC 时间:

>>> from_date = "2014/05/06 17:07"
>>> from_date = dateutil.parser.parse(from_date)
>>> utc=timezone('UTC')
>>> from_date = from_date.replace(tzinfo=timezone('Asia/Kuwait')).astimezone(utc)
>>> from_date
datetime.datetime(2014, 5, 6, 13, 55, tzinfo=<UTC>)
>>> from_date.strftime("%b %d %Y %H:%M:%S" )
'May 06 2014 13:55:00'

实际的 UTC 时间是 May 06 2014 14:06:00,我在以下位置找到:http://www.worldtimeserver.com/current_time_in_UTC.aspx 为什么 pytz 没有完全转换为实际时间。如您所见,10-11 minutes. 之间存在时差

【问题讨论】:

  • est = timezone('UTC')?那是 UTC,不是 EST..
  • 实际UTC时间是2014年5月6日14:07:00,可能性更大。 :-)
  • 科威特过去(1950 年?)的 UTC 偏移量是 +3:12:00。时区对象默认为那个。正如 Martijn 的回答所指出的,您需要对其进行本地化
  • @MartijnPieters 抱歉打错了。

标签: python pytz


【解决方案1】:

不要将datetime.replace()pytz 时区一起使用。来自pytz documentation

不幸的是,在许多时区使用标准日期时间构造函数的 tzinfo 参数“不起作用”。

它不起作用的原因是pytz 时区包含历史数据,而datetime 没有能力处理这些数据。

改用专用的timezone.localize() 方法:

>>> import dateutil.parser
>>> from pytz import timezone
>>> from_date = "2014/05/06 17:07"
>>> from_date = dateutil.parser.parse(from_date)
>>> from_date = timezone('Asia/Kuwait').localize(from_date).astimezone(timezone('UTC'))
>>> from_date
datetime.datetime(2014, 5, 6, 14, 7, tzinfo=<UTC>)
>>> from_date.strftime("%b %d %Y %H:%M:%S" )
'May 06 2014 14:07:00'

timezone.localize() 方法正确地将时区应用于天真的datetime 对象。

【讨论】:

  • 谢谢伙计。 localize(),是的。
猜你喜欢
  • 2011-07-02
  • 2018-01-03
  • 2015-02-16
  • 2020-09-01
  • 1970-01-01
  • 2015-12-09
  • 2019-07-21
  • 2015-06-13
  • 2018-07-05
相关资源
最近更新 更多