python中时间的推移

之前在写抓取天气预报信息的程序时,要得到明天和后天的日期,我思来想去用的方法是很老套的时间相加法来算的。

 

this_date = str(time.strftime("%Y/%m/%d %a"))
now = int(time.time())
sec = 24*60*60
day_today = "今天(%s号)" % str(time.strftime("%d", time.localtime(now+0*sec)))
day_tommo = "明天(%s号)" % str(time.strftime("%d", time.localtime(now+1*sec)))
day_aftom = "后天(%s号)" % str(time.strftime("%d", time.localtime(now+2*sec)))

 

 

 

现在想想真是可笑,我怎么忘记还有timedelta函数呢。。。

正解:

 

>>> from datetime import datetime,timedelta

>>> now = datetime.now()

>>> now

datetime.datetime(2010, 3, 5, 11, 28, 9, 453000)

>>> tomorrow = now + timedelta(hours=24)

>>> tomorrow

datetime.datetime(2010, 3, 6, 11, 28, 9, 453000)

>>> 

 

-END-

posted @ 2010-03-05 11:35  听风  阅读(752)  评论(0编辑  收藏  举报