如何比较Django中的datetime? [英] How to compare datetime in Django?

查看:95
本文介绍了如何比较Django中的datetime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

ds = datetime.datetime.now
dd = Entry.objects.get(pk=id).pub_date

如何比较上面的2个对象?我想得到他们之间的时差。
请帮我解决这个问题。非常感谢!

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 !

推荐答案

我假设 pub_date django.db.models.DateField ,这意味着您可以将其视为 datetime.date 对象。

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

如果将它们转换为相同的类型( datetime.datetime datetime.date ),并从另一个中减去一个,您将获得一个 datetime.timedelta 的实例。

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.

当您使用 datetime.datetime.now()时,如果您的 pub_date 只是一个日期而不是日期时间,您可以使用 ds = datetime.date.today()而不是:

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

这篇关于如何比较Django中的datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆