14

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.

Bjorn
  • 69,215
  • 39
  • 136
  • 164

4 Answers4

21

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

Ham
  • 436
  • 1
  • 4
  • 14
15

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
  • 384,516
  • 81
  • 508
  • 779
  • 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. – Bjorn Feb 01 '09 at 04:28
  • 5
    This approach, like `total_seconds()` in Python 2.7, will return an incorrect result if the days don't have 24 hours (for example, because of changes in daylight saving time). – Bruno Sep 14 '11 at 14:41
  • I have to agree with Bruno - this will give wrong results twice a year, so it's not a correct answer. – Tom Swirly Jan 31 '12 at 18:04
  • 1
    The correct value is "(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6". (for python versions less than 2.7 that can't use total_seconds) – markwatson Apr 23 '12 at 20:45
  • @markwatson it is not exactly the same total_seconds(). Looks like it is truncating the milliseconds... Thanks anyway! :-) – semente Sep 17 '12 at 20:13
5

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
  • 528,062
  • 107
  • 651
  • 834
5

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
  • 28,822
  • 30
  • 126
  • 171
  • 3
    You can further complicate things: `reduce(float.__sub__, (mktime(d.utctimetuple()) for d in (ts1, ts2)))` – jfs Feb 01 '09 at 10:04
  • @J.F.Sebastian: but why? – Claudiu Aug 06 '13 at 18:38
  • What will happen if ts1 is in one time zone and ts2 is in another? Or, they're in the same timezone but one is in Daylight Saving time and the other is not? – Qi Fan Oct 10 '15 at 01:23