最干净和最Python的方式来获取明天的date?

什么是最干净和最Pythonic方式得到明天的date? 必须有一个更好的办法,比当天增加一个,处理月末的日子等等。

datetime.date.today() + datetime.timedelta(days=1)应该做的伎俩

timedelta可以处理添加日,秒,微秒,毫秒,分钟,小时或星期。

 >>> 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) 

正如在评论中提到的那样,闰日不构成问题:

 >>> 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) 

没有处理闰秒 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' 

织补。

编辑 – @Mark:文档说“是”,但代码说“不是那么多”:

 >>> 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) 

我会认为gmtime或localtime将采用mktime返回的值,并将其返回给原始元组,其中60为秒数。 而这个testing表明,这些闰秒可以消失…

 >>> 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 

即使是基本的time模块也可以处理:

 import time time.localtime(time.time() + 24*3600)