How to perform arithmetic operation on a date in Python?

PythonDatetimePython 2.7

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionatamsView Question on Stackoverflow
Solution 1 - PythonjamylakView Answer on Stackoverflow
Solution 2 - PythonRobert RanjanView Answer on Stackoverflow