将列中的每个值添加1天

发布于 2025-01-21 14:51:36 字数 389 浏览 0 评论 0原文

我有一列日期。他们都是同一日期。 如何在该列中的每个日期价值中添加1天?

这是我的代码:

aday = dt.timedelta(days=1) 
datetickerdf = pd.read_csv('datesandtickers.csv')
datetickerdf = pd.DataFrame(datetickerdf, columns=["ticker","date"])
datetickerdf['date'] = datetickerdf['date'] + aday
datetickerdf

我会收到此错误:“ +:'timedelta''和'str”“

我如何将“ aday”转换为可用于 +运算符的东西?我想为我的专栏中的所有日期添加额外的一天。

I have a column of dates. They are all the same date.
How do I add 1 extra day to every date value in that column?

Here is my code:

aday = dt.timedelta(days=1) 
datetickerdf = pd.read_csv('datesandtickers.csv')
datetickerdf = pd.DataFrame(datetickerdf, columns=["ticker","date"])
datetickerdf['date'] = datetickerdf['date'] + aday
datetickerdf

I get this error: "unsupported operand type(s) for +: 'Timedelta' and 'str'"

How can I transform "aday" into something that can be used for the + operator? I want to add an extra day to all the dates in my column.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一人独醉 2025-01-28 14:51:36

您需要将字符串转换为日期对象。
字符串是日期对象后,您可以应用时间delta,然后将新的日期对象转回字符串。

#Assuming datetickerdf['date']  is something like 21 June, 2018
#My Delta
aday = dt.timedelta(days=1) 
#The date in the file converted to a date object
fileday = dt.datetime.strptime(datetickerdf['date'], "%d %B, %Y")
#New date calculated with delta
newday = fileday+aday
#Write it back to a file
datetickerdf['date'] = newday.strftime("%d %B, %Y")

使用此页面以获取正确的格式字符串来解析并重写字符串 https://docs.python.org/3/library/dateTime.html#strftime-strptime-behavior

You need to convert your string into a date object.
Once your string is a date object, you can apply the time delta and then turn the new date object back into a string.

#Assuming datetickerdf['date']  is something like 21 June, 2018
#My Delta
aday = dt.timedelta(days=1) 
#The date in the file converted to a date object
fileday = dt.datetime.strptime(datetickerdf['date'], "%d %B, %Y")
#New date calculated with delta
newday = fileday+aday
#Write it back to a file
datetickerdf['date'] = newday.strftime("%d %B, %Y")

Use this page to get the right format string to parse and rewrite the string https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

陈独秀 2025-01-28 14:51:36

使用pd.timedelta有一天创建DateTimelike

datetickerdf['date'] = datetickerdf['date'] + pd.Timedelta(days=1)

Use pd.Timedelta to create datetimelike one day

datetickerdf['date'] = datetickerdf['date'] + pd.Timedelta(days=1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文