Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculating the next day from a "YYYYMMDD" formatted string

How can I calculate the next day from a string like 20110531 in the same YYYYMMDD format? In this particular case, I like to have 20110601 as the result. Calculating "tomorrow" or next day in static way is not that tough, like this:

>>> from datetime import date, timedelta
>>> (date.today() + timedelta(1)).strftime('%Y%m%d')
'20110512'
>>>
>>> (date(2011,05,31) + timedelta(1)).strftime('%Y%m%d')
'20110601'

But how can I use a string like dt = "20110531" to get the same result as above?

like image 737
MacUsers Avatar asked May 11 '11 11:05

MacUsers


3 Answers

Here is an example of how to do it:

import time
from datetime import date, timedelta

t=time.strptime('20110531','%Y%m%d')
newdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1)
print newdate.strftime('%Y%m%d')
like image 182
AJ. Avatar answered Nov 03 '22 21:11

AJ.


>>> from datetime import datetime
>>> print datetime.strptime('20110531', '%Y%m%d')
2011-05-31 00:00:00

And then do math on that date object as you show in your question.

The datetime library docs.

like image 39
Brandon Rhodes Avatar answered Nov 03 '22 21:11

Brandon Rhodes


You are most of the way there! along with the strftime function which converts a date to a formatted string, there is also a strptime function which converts back the other way.

To solve your problem you can just replace date.today() with strptime(yourDateString, '%Y%m%d').

ED: and of course you will also have to add strptime to the end of your from datetime import line.

like image 42
verdesmarald Avatar answered Nov 03 '22 23:11

verdesmarald