如何使用Pandas Timestamp在Python中找到特定日期到现在的经过时间?

1 投票
1 回答
39 浏览
提问于 2025-04-13 21:15

我有一个数据表,里面记录了一些公司的信息:

公司名称 成立时间
a 2004年1月1日 00:00:00
b 2013年1月1日 00:00:00
c 2008年1月1日 00:00:00
d 1997年1月1日 00:00:00
today = pd.Timestamp.now()
df["founded_on"]=pd.to_datetime(df["founded_on"])
df["Time_Since_founded_on"] = (today - df["founded_on"]).dt.days // 30

出现了一个错误:OverflowError:在int64加法中溢出。

我想知道每个公司运营了多少个月。

1 个回答

1

使用按月的操作,可以通过 to_period('M') 来进行转换:

df['Time_Since_founded_on'] = (pd.to_datetime(df['founded_on']).dt.to_period('M')
                                 .rsub(pd.Timestamp('today').to_period('M'))
                                 .apply(lambda x: x.n)
                              )

输出结果:

  company_name           founded_on  Time_Since_founded_on
0            a  2004-01-01 00:00:00                    242
1            b  2013-01-01 00:00:00                    134
2            c  2008-01-01 00:00:00                    194
3            d  1997-01-01 00:00:00                    326

注意,你原来的方法(使用天数)在处理较长时间段时会给出错误的值,因为一个月并不等于30天:

df['Time_Since_founded_on'] = (pd.to_datetime(df['founded_on'])
                                 .rsub(pd.Timestamp('today'))
                                 .dt.days.div(30)
                              )

  company_name           founded_on  Time_Since_founded_on
0            a  2004-01-01 00:00:00             246.066667  # +4M
1            b  2013-01-01 00:00:00             136.466667  # +2M
2            c  2008-01-01 00:00:00             197.366667  # +3M
3            d  1997-01-01 00:00:00             331.266667  # +5M

一个更好的(但并不完美的)近似方法是用 365.25/12 来进行计算。

处理无效或缺失的日期

如果日期无效或缺失,你需要调整代码,使用 errors='coerce'dropna,然后再提取月份的数量:

df['Time_Since_founded_on'] = (pd.to_datetime(df['founded_on'], errors='coerce')
                                 .dt.to_period('M')
                                 .rsub(pd.Timestamp('today').to_period('M'))
                                 .dropna().apply(lambda x: x.n)
                              )

输出结果:

  company_name           founded_on  Time_Since_founded_on
0            a  2004-01-01 00:00:00                  242.0
1            b  2013-01-01 00:00:00                  134.0
2            c  2008-01-01 00:00:00                  194.0
3            d  1997-01-01 00:00:00                  326.0
4            e                  NaT                    NaN

撰写回答