【问题标题】:Getting crazy with UTC offset in python (to_datetime panda function and datetime object)对 python 中的 UTC 偏移量感到疯狂(to_datetime pandas 函数和 datetime 对象)
【发布时间】:2019-12-27 21:15:56
【问题描述】:

几个小时以来,我对这个话题变得无精打采......

作为输入,我将时间戳作为字符串存储在列表中:

0     Sat Mar 30 2019 21:00:00 GMT+0100
1     Sat Mar 30 2019 22:00:00 GMT+0100
2     Sat Mar 30 2019 23:00:00 GMT+0100

当我将它们转换为日期时间对象时,时区会反转:

GC['date'] = pd.to_datetime(my_timestamps)
0     2019-03-30 21:00:00-01:00
1     2019-03-30 22:00:00-01:00
2     2019-03-30 23:00:00-01:00

我已经仔细检查了 GMT+1 在 Google 上的含义。

考虑到 UTC 时间 9 点,GMT+1 时间是 10 点:它比 UTC 多 1 小时。

所以要获得 UTC,您应该将 GMT+1 时间偏移 -1 小时。

因此,我可以在偏移量中使用 -1:

0     2019-03-30 21:00:00-01:00

现在,当我尝试“解决”偏移时,我得到:

GC['date2'] = pd.to_datetime(my_timestamps, utc=True)
0    2019-03-30 22:00:00+00:00
1    2019-03-30 23:00:00+00:00
2    2019-03-31 00:00:00+00:00

OMG,偏移量被反转了。 好的,让我们再次与 Google 确认一下:

https://pythontic.com/datetime/datetime/utcoffset

代码的输出是新加坡与 UTC 的 +8 小时偏移

Singapore Time instance:2017-02-14 12:15:01.000099+08:00
UTC Offset for Singapore Time:8:00:00

从新加坡时间开始,要找到 UTC 时间,你必须减去这 8 个小时:

Singapore time: 5 hour AM
UTC time: 21 hour PM

所以问题出现在转换步骤 GMT+1 -> -01:00 in to_datetime。

请问,有人知道如何解决这个问题吗? 预先感谢您的帮助。

最佳,

皮埃尔

【问题讨论】:

  • 你确定不对,我得到的时间戳对象是 Timestamp('2019-03-30 21:00:00-0100', tz='tzoffset(None, -3600)') , datetime.datetime(2019, 3, 30, 21, 0, tzinfo=tzoffset(None, -3600))
  • 您好,我已将其提交给 pandas Github bugtracker。我认为以 iso 格式重写时,GMT+1h 应该保持 UTC+1h。在将这些时间戳设置为我的数据帧的索引并激活 verify_integrity 时,我看到了麻烦:由于这个 trouble(我还不敢称其为错误),此检查确定了重复索引。我会报告熊猫团队的任何反馈

标签: python pandas datetime


【解决方案1】:

这不是一个完整的答案,但我已经找到了错误所在。 pandas 是calling dateutils 解析函数来进行实际解析,该函数有错误。

>>from dateutil.parser import parse  
>>parse('Sat Mar 30 2019 21:00:00 GMT+0100')
datetime.datetime(2019, 3, 30, 21, 0, tzinfo=tzoffset(None, -3600))
>>parse('Sat Mar 30 2019 21:00:00+0100')
datetime.datetime(2019, 3, 30, 21, 0, tzinfo=tzoffset(None, 3600))

注意第一个输出中的 -3600,而第二个输出中应该是 +3600。

但是从 dateutil 的角度来看,当时间戳指定为 GMT+int 时,这看起来像是“预期的”行为。来自dateutil parase function

  # Check for something like GMT+3, or BRST+3. Notice
  # that it doesn't mean "I am 3 hours after GMT", but
  # "my time +3 is GMT". If found, we reverse the
  # logic so that timezone parsing code will get it
  # right.

因此,他们将 GMT+1 解释为“我的时间加上 1 小时将是 GMT”,这对我来说是一种非常不标准的解释。

【讨论】:

  • 你好 Rajendra,是的,我在 pandas Github 中发布了一个但他们将我重新定向到 dateutil。请问,您的建议是什么作为解决方法?我发现了这个堆栈溢出问题,它提出了一个问题。我正要试一试。 stackoverflow.com/questions/31078749/…
  • @pierre_j 是的,这看起来像是一个标准问题。我建议您在原始源文件中进行查找和替换,以完全删除“GMT”。然后它将被正确解析。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 2011-03-22
相关资源
最近更新 更多