gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:00:44 25 4
gpt4 key购买 nike

我从有类似问题的其他人那里获得了以下代码,但建议的解决方案不适用于我的 DataFrame。该代码从给定日期中减去 Pandas DataFrame 索引:

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

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

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

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

最佳答案

这是一个使用 J.F. Sebastian 的评论的答案,真的要感谢他,因为你的索引有时区信息,那么操作也必须是时区感知的,在你的情况下,时区是 utc,所以你需要生成一个 utc 时间戳来执行减法:

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

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

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

与非时区感知索引比较:

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

关于python - 具有不同时区的时间数组的时间戳减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28254408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com