11

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?

timko.mate
  • 345
  • 1
  • 3
  • 13

1 Answers1

49

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'
Community
  • 1
  • 1
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148