[Django]-How do I subtract two dates in Django/Python?

69๐Ÿ‘

โœ…

You can just subtract the dates directly, which will yield a datetime.timedelta object:

dt = weight_now.weight_date - weight_then.weight_date

A timedelta object has fields for days, seconds, and microseconds. From there, you can just do the appropriate math. For example:

hours = dt.seconds / 60 / 60    # Returns number of hours between dates
weeks = dt.days / 7             # number of weeks between dates
๐Ÿ‘คmipadi

37๐Ÿ‘

Django datetime objects are just regular Python datetime objects. When you subtract one datetime from another you get a timedelta object.

If you are looking to subtract a length of time from a datetime you need to subtract a timedelta object from it. For example:

>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> print now
2010-05-18 23:16:24.770533
>>> this_time_yesterday = now - timedelta(hours=24)
>>> print this_time_yesterday
2010-05-17 23:16:24.770533
>>> (now - this_time_yesterday).days
1
๐Ÿ‘คDan Head

5๐Ÿ‘

Note that subtracting will not work in case the two date times have different offset-awareness, e.g., one with tzinfo and one without (native).

๐Ÿ‘คItkovian

Leave a comment