Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 1 day to my date in Python [duplicate]

Tags:

python

date

I have the following date format:

year/month/day

In my task, I have to add only 1 day to this date. For example:

date = '2004/03/30'
function(date)
>'2004/03/31'

How can I do this?

like image 492
timko.mate Avatar asked May 07 '16 14:05

timko.mate


People also ask

How do you increase days in Python?

Add Days to datetime Object If we want to add days to a datetime object, we can use the timedelta() function of the datetime module. The previous Python syntax has created a new data object containing the datetime 2024-11-24 14:36:56, i.e. 18 days later than our input date.


Video Answer


1 Answers

You need the datetime module from the standard library. Load the date string via strptime(), use timedelta to add a day, then use strftime() to dump the date back to a string:

>>> from datetime import datetime, timedelta
>>> s = '2004/03/30'
>>> date = datetime.strptime(s, "%Y/%m/%d")
>>> modified_date = date + timedelta(days=1)
>>> datetime.strftime(modified_date, "%Y/%m/%d")
'2004/03/31'
like image 139
alecxe Avatar answered Oct 01 '22 19:10

alecxe