如何在Django中计算两个日期之间的差异

chhkpiq4  于 2023-10-21  发布在  Go
关注(0)|答案(3)|浏览(135)

我想计算当前日期和前一日期之间的天数差异。我正在尝试这个代码

requiremntObj = CustomerLeads.objects.all()
a = datetime.datetime.now().date()

for i in requiremntObj:
    date1=i.posting_date
    diff = a-date1
    print diff

我得到了一个错误unsupported operand type(s) for -: 'datetime.date' and 'unicode'
对于当前日期,我获取datetime对象,对于日期1,我获取unicode。

posting_date = models.DateField()
9ceoxa92

9ceoxa921#

如果你有DateTimeField,你可以用途:

delta = datetime.now().date() - posting_date
print delta.days

如果它是字符串,那么你必须转换:

from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime(str(datetime.now().date()), date_format)
b = datetime.strptime(str(posting_date), date_format)
delta = b - a
print delta.days

这里是post

iezvtpos

iezvtpos2#

Django中的HTML代码

<p> {{ to_date|timeuntil:from_date }} </p>

此代码用于python中的服务器站点

import datetime

from_date = datetime.datetime(2019, 10, 21)

to_date   = datetime.datetime(2019, 10, 25)

result = to_date - from_date
print(result.days)
ktecyv1j

ktecyv1j3#

导入这些模块

from django.utils import timezone
from datetime import timedelta

created_on = user.datetime_created.date()
today = timezone.now().date()
diff = (today-created_on).days

相关问题