开发者

Python--Timedelta expression ignoring days (treating 6 mins the same as 24 hours + 6mins)

I'm trying to calculate the number of hours since a post has gone live. It works, except it treats 24 hours later as 0 hours. In other words, it seems to just subtract the current time from the baseline time without taking into consideration day differentials.

    def hours_live(self):
         diff=((datetime.datetime.today() - self.created).seconds)/3600
         return '%d Hours Ago' %diff
开发者_JAVA技巧

self.created refers to a Django DateTimeField:

      created=models.DateTimeField(auto_now_add=True)

What am I missing about the datetime object here?


You want total_seconds(), not seconds.


Don't forget you can use Django timesince filter too as an option :)

>>> import datetime
>>> past = datetime.datetime.now() - datetime.timedelta(hours=6, minutes=20)
>>>
>>> from django.template.defaultfilters import timesince
>>> timesince(past)
u'6 hours, 20 minutes'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜