django如何从django datetime.date类中减去日期

时间:2018-11-21 11:41:15

标签: django date

我有一个模特:

class DateModel(models.Model):
    date = models.DateField(default=None, null=True, blank=True)

我做了一些物体并得到它:

date_obj = GroupDate.objects.all().last()
print(date_obj.date)
print(type(date_obj.date))

以便它返回以下行:

2018-11-21
<class 'datetime.date'>

这是我的问题,

如何从日期222018-11-21天前获取

赞:

date_obj = GroupDate.objects.all().last()
some_int = 22
result_date = get_date_from_date(date_obj.date, some_int) # It is just example that I made.
print(result_date) # >>>2018-10-30

我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用timedelta

>>> from datetime import datetime, timedelta
>>> date_obj = datetime(2018, 11, 21)
>>> some_int = 22
>>> result_date = date_obj - timedelta(days = some_int)
>>> result_date
datetime.datetime(2018, 10, 30, 0, 0)

您还可以使用relativedelta中的dateutil,这是一个功能更强大的库,具有更多选项,文档也已链接。

>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> date_obj = datetime(2018, 11, 21)
>>> some_int = 22
>>> result_date = date_obj - relativedelta(days =+ some_int)
>>> result_date
datetime.datetime(2018, 10, 30, 0, 0)