'Add +1 day to each value in the column
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.
Solution 1:[1]
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
Solution 2:[2]
Use pd.Timedelta to create datetimelike one day
datetickerdf['date'] = datetickerdf['date'] + pd.Timedelta(days=1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NickP |
| Solution 2 | Ynjxsjmh |
