我在处理时间/时区时遇到一些困难。我有以下形式的原始 JSON 数据
{
"Date": "28 Sep 2009 00:00:00",
....
}
然后将该数据加载到 MongoDB 中,并将日期的字符串表示形式转换为JavaScript 日期对象。这个转换为UTC时间结果为以下日期
{
"_id": ObjectId("577a788f4439e17afd4e21f7"),
"Date": ISODate("2009-09-27T23:00:00Z")
}
它“看起来”好像日期实际上已经向前移动了一天,我假设(可能是错误的)这是因为我的机器设置为爱尔兰标准时间.
然后我从 MongoDB 读取这些数据并用它来创建 pandas日期时间索引
idx = pd.DatetimeIndex([x['Date'] for x in test_docs], freq='D')
这给了我
![enter image description here](https://i.stack.imgur.com/fOTbW.png)
这是不正确的,因为时间尚未从 UTC 正确转换回本地时间。所以我按照中给出的解决方案进行操作这个答案
idx = pd.DatetimeIndex([x['Date'] for x in test_docs], freq='D')
idx = idx.tz_localize(tz=tz.tzutc())
idx = idx.tz_convert(tz=tz.tzlocal())
frame = DataFrame(test_docs, index=idx)
frame = frame.drop('Date', 1)
这给了我正确的一天回来
![enter image description here](https://i.stack.imgur.com/FuuyI.png)
I then 正常化DatetimeIndex 因此小时被删除,允许我按天对所有条目进行分组。
frame.groupby(idx).sum()
然而此时,奇怪的事情发生了。日期最终分组如下
![enter image description here](https://i.stack.imgur.com/iwZMs.png)
但这并不反映框架中的日期
![enter image description here](https://i.stack.imgur.com/Z2CN6.png)
任何人都可以阐明我可能出错的地方吗?
对@ptrj的回复
明确使用我的时区作为字符串
idx = pd.DatetimeIndex([x['Date'] for x in test_docs], freq='D')
idx = idx.tz_localize(tz=tz.tzutc())
idx = idx.tz_convert(tz='Europe/Dublin')
idx = idx.normalize()
frame = DataFrame(test_docs, index=idx)
...
...
aggregate = frame.groupby(idx).sum()
aggregate.plot()
这对我不起作用,它会导致以下情节
![enter image description here](https://i.stack.imgur.com/zxXtj.png)
由于某种原因,2014 年的 groupby 没有正确分组,如下所示
![enter image description here](https://i.stack.imgur.com/zEkBc.png)
如果相反,我使用
idx = idx.tz_convert(tz.gettz('Europe/Dublin'))
我遇到同样的问题
转换为对象
idx = pd.DatetimeIndex([x['Date'] for x in test_docs], freq='D')
idx = idx.tz_localize(tz=tz.tzutc())
idx = idx.tz_convert(tz=tz.tzlocal())
idx = idx.normalize()
frame = DataFrame(test_docs, index=idx)
aggregate = frame.groupby(idx.astype(object)).sum()
这种方法似乎对我来说是正确的
![enter image description here](https://i.stack.imgur.com/1mUJ5.png)