I\'m working on a little fitness tracker in order to teach myself Django. I want to graph my weight over time, so I\'ve decided to use the Python Google Charts Wrapper. Goog
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
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
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).