How to perform arithmetic operation on a date in Python?

Question:

I have a date column in csv file say Date having dates in this format 04/21/2013 and I have one more column Next_Day. In Next_Day column I want to populate the date which comes immediately after the date mentioned in date column. For eg. if date column has 04/21/2013 as date then I want 04/22/2013 in Next_Day column.

We can use +1 in excel but I don’t know how to perform this in Python.

Please help me in resolving this.

Asked By: atams

||

Answers:

Using datetime.timedelta

>>> import datetime
>>> s = '04/21/2013'
>>> d = datetime.datetime.strptime(s, '%m/%d/%Y') + datetime.timedelta(days=1)
>>> print(d.strftime('%m/%d/%Y'))
04/22/2013
Answered By: jamylak

Same answer as a one-liner. Prints 1 day 1 hour & 30 minutes ago from now:

python -c 'import datetime;print(datetime.datetime.now() - datetime.timedelta(days=1,hours=1,minutes=30))'

2022-02-08 13:11:06.304608
Answered By: Robert Ranjan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.