具有不同时区的时间数组的时间戳减法

具有不同时区的时间数组的时间戳减法

本文介绍了具有不同时区的时间数组的时间戳减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有其他人遇到类似问题的以下代码,但提出的解决方案不适用于我的DataFrame.该代码从给定日期减去Pandas DataFrame索引:

I have the following code from somebody else that has a similar problem, but the solution proposed does not work on my DataFrame. The code subtracts a Pandas DataFrame index from a given date:

my_date = pd.datetime.today()
MyDF['day_differential'] = (MyDF.index - my_date).days

哪个在我的DataFrame中生成以下错误:

Which is generating the following error in my DataFrame:

TypeError: Timestamp subtraction must have the same timezones or no timezones

如何找到两个日期的tz?如何使它们相同,以便可以计算它们之间的天数?

How do I found out tz for both dates? How do I make them the same so I can calculate the number of days between them?

推荐答案

在此,我非常感谢JF Sebastian的评论,因为您的索引具有时区信息,所以操作也必须了解时区,在您的情况下是时区是utc,因此您需要生成一个utc时间戳以执行减法操作:

Here is an answer using J.F. Sebastian's comment thanks really to him, because your index has timezone information then the operations must also be timezone aware, in your case the timezone is utc so you need to generate a utc timestamp to perform the subtraction:

In [11]:

import pandas as pd
import numpy as np
import datetime as dt
my_date = pd.datetime.today()
MyDF = pd.DataFrame({'a':np.random.randn(5)})
MyDF.index = pd.date_range('1/1/2011', periods=5, freq='H', tz='utc')
MyDF['day_differential'] = MyDF.index.tz_convert(None) - dt.datetime.utcnow()
MyDF
Out[11]:
                                  a            day_differential
2011-01-01 00:00:00+00:00  1.399602 -1493 days +13:04:06.875715
2011-01-01 01:00:00+00:00 -1.962517 -1493 days +14:04:06.875715
2011-01-01 02:00:00+00:00 -1.574531 -1493 days +15:04:06.875715
2011-01-01 03:00:00+00:00 -0.224702 -1493 days +16:04:06.875715
2011-01-01 04:00:00+00:00 -0.800772 -1493 days +17:04:06.875715

您可以通过输出索引来找出索引是否支持时区:

You can find out if your index is timezone aware by ouputting the index:

In [12]:

MyDF.index
Out[12]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-01 00:00:00+00:00, ..., 2011-01-01 04:00:00+00:00]
Length: 5, Freq: H, Timezone: UTC

与非时区感知索引进行比较:

compare with a non timezone aware index:

In [14]:

MyDF.index
Out[14]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-01 00:00:00, ..., 2011-01-01 04:00:00]
Length: 5, Freq: H, Timezone: None

这篇关于具有不同时区的时间数组的时间戳减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:28