Philip Mutua
Philip Mutua

Reputation: 6871

How to calculate DateTime fields in django

Suppose I have the following Date time fields and I would like to calculate the total time between them. Which is the best approach?

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)

Upvotes: 0

Views: 1018

Answers (2)

JPG
JPG

Reputation: 88459

You can simply use - operator to calculate the time difference. The result will be a time delta object.

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"


This function returns the difference in seconds and it will handle TypeError exception if one of the input is a None type. ( You defined it as null=True in models)

Upvotes: 1

Lemayzeur
Lemayzeur

Reputation: 8525

Django DateTime Fields are like datetime object of python, to calculate the total time between, you need to substract one from another one since they are same objects. This is an approach

result = datetime1 - datetime2
result.seconds # To have the output in seconds

In your case:

total_time = (checked_in_at - discharged_at).seconds

Upvotes: 2

Related Questions