The cleanest and most Pythonic way to get a date tomorrow?

What is the cleanest and most Pythonic way to get a date tomorrow? There should be a better way than adding one day, processing days at the end of the month, etc.

+65
python date datetime time
01 Oct '09 at 22:45
source share
4 answers

datetime.date.today() + datetime.timedelta(days=1) should do the trick

+128
01 Oct '09 at 22:49
source share

timedelta can handle the addition of days, seconds, microseconds, milliseconds, minutes, hours or weeks.

 >>> import datetime >>> today = datetime.date.today() >>> today datetime.date(2009, 10, 1) >>> today + datetime.timedelta(days=1) datetime.date(2009, 10, 2) >>> datetime.date(2009,10,31) + datetime.timedelta(hours=24) datetime.date(2009, 11, 1) 

As stated in the comment, days of leap problems are not a problem:

 >>> datetime.date(2004, 2, 28) + datetime.timedelta(days=1) datetime.date(2004, 2, 29) >>> datetime.date(2004, 2, 28) + datetime.timedelta(days=2) datetime.date(2004, 3, 1) >>> datetime.date(2005, 2, 28) + datetime.timedelta(days=1) datetime.date(2005, 3, 1) 
+28
01 Oct '09 at 22:49
source share

No handling seconds jump tho:

 >>> from datetime import datetime, timedelta >>> dt = datetime(2008,12,31,23,59,59) >>> str(dt) '2008-12-31 23:59:59' >>> # leap second was added at the end of 2008, >>> # adding one second should create a datetime >>> # of '2008-12-31 23:59:60' >>> str(dt+timedelta(0,1)) '2009-01-01 00:00:00' >>> str(dt+timedelta(0,2)) '2009-01-01 00:00:01' 

darn.

EDIT - @Mark: The docs say yes, but the code says not so much:

 >>> time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S") (2008, 12, 31, 23, 59, 60, 2, 366, -1) >>> time.mktime(time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S")) 1230789600.0 >>> time.gmtime(time.mktime(time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S"))) (2009, 1, 1, 6, 0, 0, 3, 1, 0) >>> time.localtime(time.mktime(time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S"))) (2009, 1, 1, 0, 0, 0, 3, 1, 0) 

I would think that gmtime or localtime will take the value returned by mktime and return the original tuple, and 60 as the number of seconds. And this test shows that these seconds of jump can just disappear ...

 >>> a = time.mktime(time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S")) >>> b = time.mktime(time.strptime("2009-01-01 00:00:00","%Y-%m-%d %H:%M:%S")) >>> a,b (1230789600.0, 1230789600.0) >>> ba 0.0 
+5
01 Oct '09 at 23:45
source share

Even the base time module can handle this:

 import time time.localtime(time.time() + 24*3600) 
+4
01 Oct '09 at 23:58
source share



All Articles