How do I subtract two dates in Django/Python?

前端 未结 3 1864
我寻月下人不归
我寻月下人不归 2020-12-15 03:29

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

相关标签:
3条回答
  • 2020-12-15 03:50

    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
    
    0 讨论(0)
  • 2020-12-15 03:52

    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
    
    0 讨论(0)
  • 2020-12-15 03:54

    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).

    0 讨论(0)
提交回复
热议问题