views:

1365

answers:

5

I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.

Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want.

Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something?

It would be perfect if I could just get the entire difference in seconds.

+7  A: 

You can compute the difference in seconds.

total_seconds = delta.days * 86400 + delta.seconds

No, you're no "missing something". It doesn't provide deltas in seconds.

S.Lott
That's what I plan on doing, but I just didn't want that kludge in my code if there was something I didn't know about. Thanks.
apphacker
Wish they had .total_seconds, .total_minutes, etc etc on timedeltas...
romkyns
+1  A: 

It would be perfect if I could just get the entire difference in seconds.

Then plain-old-unix-timestamp as provided by the 'time' module may be more to your taste.

I personally have yet to be convinced by a lot of what's in 'datetime'.

bobince
+1  A: 

Like bobince said, you could use timestamps, like this:

# assuming ts1 and ts2 are the two datetime objects
from time import mktime
mktime(ts1.timetuple()) - mktime(ts2.timetuple())

Although I would think this is even uglier than just calculating the seconds from the timedelta object...

itsadok
You can further complicate things: `reduce(float.__sub__, (mktime(d.utctimetuple()) for d in (ts1, ts2)))`
J.F. Sebastian
A: 

This actually isnt a big deal. Wish I knew how to remove comments. I left a negative one here earlier, but realized after reading some of the code above that I overreacted. Simple work around! Thanks :)

+1  A: 

It seems that Python 2.7 has introduced a total_seconds() method, which is what you were looking for, I believe!

Ham