pandaZW pandaZW - 9 days ago 6
Python Question

How to compare two datetime by day in Django?

from django.utils import timezone


good = Goods.objects.get(id=num)
now = timezone.now()

print(good.create_time)
print(now)


How to compare these whether they are by one day.

2016-12-01 10:21:32.746505+00:00
2016-12-01 10:24:08.906268+00:00

Answer

Use a timedelta:

d1 = datetime(year=2016, month=12, day=1)
d2 = datetime(year=2016, month=12, day=2)

abs(d2 - d1) < timedelta(days=1)

Or if you just want to compare the day, you can access it from the .day attribute:

d1.day # 1
d2.day # 2