How do I subtract two dates in Django/Python?

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

Leave a Comment

404 Not Found

Not Found

The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.