如何在Python中使用datetime进行减法操作

huangapple go评论71阅读模式
英文:

How to subtract using datetime in py

问题

我有一个数据集,想要创建一个新的列,该列从start_Date列往前看90天。我尝试了两种方法,都导致了类型错误。

df['prior_date'] = df['start_Date'] - 90

我还尝试了

df['prior'] = (df['start_Date'] - dt(days=90)).strftime('%Y-%m-%D')

有关如何使创建的列prior正常工作的建议吗?谢谢。

英文:

I have a dataset and would like to create a new column that looks 90 days back from the start_Date column. I have tried two ways and both cause a typeError.

df['prior_date'] = df['start_Date'] - 90

And I tried

df['prior'] = (df['start_Date')] - dt(days = 90)).strftime('%Y-%m-%D')

Any suggestions on how to have the created column prior work? Thank you

答案1

得分: 1

使用pandas的timedelta方法:

df['prior_date'] = df['start_Date'] - pd.Timedelta(90, "d")
英文:

Use pandas' timedelta method:

df['prior_date'] = df['start_Date'] - pd.Timedelta(90, "d")

huangapple
  • 本文由 发表于 2023年6月12日 06:29:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452764.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定