开发者

How to compare datetime in Django?

开发者 https://www.devze.com 2022-12-13 15:55 出处:网络
Suppose I have: ds = datetime.datetime.now dd = Entry.objects.get(pk=id).pub_date 开发者_如何学JAVA

Suppose I have:

ds = datetime.datetime.now
dd = Entry.objects.get(pk=id).pub_date
开发者_如何学JAVA

How to compare 2 objects above? I want to get the time difference between them. Please help me solve this problem. Thank you very much !


I am assuming that pub_date is a django.db.models.DateField, which means you can treat it as a datetime.date object.

If you convert them to the same type (either datetime.datetime or datetime.date) and subtract one from the other, you will get an instance of datetime.timedelta.

As you are using datetime.datetime.now(), if your pub_date is simply a date rather than a datetime, you may as well use ds = datetime.date.today() instead:

>>> ds = datetime.date.today()
>>> dd = datetime.date(2009, 12, 9)
>>> ds - dd
datetime.timedelta(2) # 2 days ago
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号