获取明天约会的最干净,最Python方式是什么?必须有比在一天中增加一天,在月末处理天等等的更好的方法。
获取明天约会的最干净,最Python方式是什么?必须有比在一天中增加一天,在月末处理天等等的更好的方法。
Answers:
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)
如评论中所问,leap日没有问题:
>>> 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)
没有处理的闰秒寿:
>>> 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秒为单位返回给我原始的元组。该测试表明这些leap秒会逐渐消失...
>>> 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)
>>> b-a
0.0
即使是基本time
模块也可以处理此问题:
import time
time.localtime(time.time() + 24*3600)
time.strftime
手柄闰秒:见注2:docs.python.org/library/time.html#time.strftime和注3:docs.python.org/library/datetime.html#strftime-behavior