如何用python减去日期

时间:2011-02-01 14:51:03

标签: python datetime

今天=

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

90天前

DD = datetime.timedelta(days=-90)

今天如何获得 - DD或90天前?

4 个答案:

答案 0 :(得分:35)

您应该能够从日期时间对象中减去时间增量。

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

答案 1 :(得分:12)

只需从日期时间中减去timedelta:

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

(或者如果你想像你那样使用负时间值,请添加它们:

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

答案 2 :(得分:6)

您需要减去timedelta(days=90)

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

应该{​​{3}} 2010-11-03 15:04:42.289684

答案 3 :(得分:2)

from datetime import date,timedelta

currentDay = date.today()

requestedDay = currentDay - timedelta(days=90)

print(requestedDay)
希望它能解决。