在python中使用UTC偏移量变得疯狂(to_datetime熊猫函数和datetime对象)

时间:2019-12-27 21:15:56

标签: python pandas datetime

自从几个小时以来,我对此话题一无所知...

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

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

当我将它们转换为datetime对象时,时区相反:

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

因此,问题似乎出在to_datetime中的转换步骤GMT + 1-> -01:00期间。

请,有人对如何解决这个问题有想法吗? 我先感谢您的帮助。

最好

皮埃尔

1 个答案:

答案 0 :(得分:1)

这不是一个完整的答案,但是我已经找到了错误所在。 大熊猫是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”,这对我来说似乎是一种非标准的解释。