Python 如何在django中计算DateTime字段

Python 如何在django中计算DateTime字段,python,django,python-3.x,Python,Django,Python 3.x,假设我有以下日期时间字段,我想计算它们之间的总时间。哪种方法最好 session_end_time = models.DateTimeField(null=True, blank=True) discharged_at = models.DateTimeField(null=True, blank=True) checked_in_at = models.DateTimeField(null=True, blank=True) DjangoDateTime字段类似于python的DateTim

假设我有以下日期时间字段,我想计算它们之间的总时间。哪种方法最好

session_end_time = models.DateTimeField(null=True, blank=True)
discharged_at = models.DateTimeField(null=True, blank=True)
checked_in_at = models.DateTimeField(null=True, blank=True)

Django
DateTime
字段类似于python的
DateTime
object,要计算两者之间的总时间,需要从一个字段中减去另一个字段,因为它们是相同的对象。这是一种方法

result = datetime1 - datetime2
result.seconds # To have the output in seconds
就你而言:

total_time = (checked_in_at - discharged_at).seconds

Django
DateTime
字段类似于python的
DateTime
object,要计算两者之间的总时间,需要从一个字段中减去另一个字段,因为它们是相同的对象。这是一种方法

result = datetime1 - datetime2
result.seconds # To have the output in seconds
就你而言:

total_time = (checked_in_at - discharged_at).seconds

您可以简单地使用
-
运算符来计算时间差。结果将是一个
时间增量
对象。

def time_diff(time1, time2):
    "retun time2-time1 in 'seconds' "
    if time1 and time2:
        return (time2 - time1).seconds
    return "one of the input is None"

此函数以秒为单位返回差值,如果其中一个输入是
None
类型,它将处理
TypeError
异常。(
您在
模型中将其定义为
null=True

您可以简单地使用
-
运算符来计算时间差。结果将是一个
时间增量
对象。

def time_diff(time1, time2):
    "retun time2-time1 in 'seconds' "
    if time1 and time2:
        return (time2 - time1).seconds
    return "one of the input is None"

此函数以秒为单位返回差值,如果其中一个输入是
None
类型,它将处理
TypeError
异常。(
您在
模型

中将其定义为
null=True
-
运算符?是
-
运算符吗?