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.
CodePudding user response:
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
CodePudding user response:
Use pd.Timedelta
to create datetimelike one day
datetickerdf['date'] = datetickerdf['date'] pd.Timedelta(days=1)