pandas 中的时间戳超出范围

问题描述 投票:0回答:2

我需要将一些sql代码重写为python,我的问题是计算天数差异的必要性: 如您所见,对于 Final_pmt_date ‘9999-12-31’ 的情况,可以轻松减去日期。

但是在 pandas 中,datetime64 类型有限制,所以我得到了异常:

我看到的所有答案都是关于将此日期转换为 NaN (使用“coerce”关键字)。但我还需要计算此类日期时间的天数。

提前谢谢您

python pandas datetime timestamp
2个回答
1
投票

9999-12-31
这样的日期超出了pandas日期时间的范围

使用 vanilla Python datetime 可能是一种替代方案,例如喜欢

from datetime import datetime
import pandas as pd

df = pd.DataFrame(
    {
        "open": ["2021-12-27 00:00:00.000", "2019-03-06 00:00:00.000"],
        "close": ["9999-12-31 00:00:00.000", "2022-04-06 00:00:00.000"],
    }
)

df["delta"] = df.apply(
    (
        lambda row: datetime.fromisoformat(row["close"])
        - datetime.fromisoformat(row["open"]),
    ),
    axis=1,
)

df
                      open                    close                  delta
0  2021-12-27 00:00:00.000  9999-12-31 00:00:00.000  2913908 days, 0:00:00
1  2019-03-06 00:00:00.000  2022-04-06 00:00:00.000     1127 days 00:00:00

但是请注意,您必须使用

apply
,与“矢量化”pandas 日期时间方法相比,这不是很有效。也许使用
NaT
作为“无效值标识符”毕竟是一个选项?


0
投票

另一种方法是使用Period_Index,如下所述:Pandas docs

这里提到了频率:周期别名

import pandas as pd

s = pd.Series(["3020-01-01", "2020-01-01"])
e = pd.Series(["3025-01-01", "2020-01-01"])
df= pd.DataFrame({'start':s, 'end':e})

df.start= pd.PeriodIndex(df.start, freq='D') # convert to Period_Index
df.end= pd.PeriodIndex(df.end, freq='D') # convert to Period_Index
df['duration'] = df['start'] - df['end']
df['days']= df.duration.apply(lambda x: x.n)
© www.soinside.com 2019 - 2024. All rights reserved.