2011-02-01 109 views
13

今天日期=如何減去與蟒蛇

today = datetime.datetime.now().strftime("%Y%m%d") 

90天前

DD = datetime.timedelta(days=-90) 

如何獲得今天 - DD,或者90天前?

+0

你從哪裏學習`datetime`模塊和`timedelta`類? – SilentGhost 2011-02-01 14:57:11

回答

26

您應該能夠從日期時間對象中減去時間變化量。

today = datetime.datetime.now() 
DD = datetime.timedelta(days=90) 
earlier = today - DD 
earlier_str = earlier.strftime("%Y%m%d") 
4

你需要減去timedelta(days=90)

from datetime import date, datetime, timedelta 
today = datetime.now() 
dd = today - timedelta(days=90) 
print(dd) 

它應該print2010-11-03 15:04:42.289684

+1

是的,那麼答案是什麼? – SilentGhost 2011-02-01 14:58:38

11

剛剛從日期時間減去timedelta:

>>> import datetime 
>>> today = datetime.datetime.today() 
>>> DD = datetime.timedelta(days=90) 
>>> today - DD 
datetime.datetime(2010, 11, 3, 9, 56, 20, 924224) 

(或者,如果你要使用像你這樣有負timedelta,添加它們:

>>> DD = datetime.timedelta(days=-90) 
>>> today + DD 
datetime.datetime(2010, 11, 3, 9, 56, 20, 924224) 
2
from datetime import date,timedelta 

currentDay = date.today() 

requestedDay = currentDay - timedelta(days=90) 

print(requestedDay) 

希望它解決了。