How can I produce a human readable difference when subtracting two UNIX timestamps using Python?

Viewed 39680

This question is similar to this question about subtracting dates with Python, but not identical. I'm not dealing with strings, I have to figure out the difference between two epoch time stamps and produce the difference in a human readable format.

For instance:

32 Seconds
17 Minutes
22.3 Hours
1.25 Days
3.5 Weeks
2 Months
4.25 Years

Alternately, I'd like to express the difference like this:

4 years, 6 months, 3 weeks, 4 days, 6 hours 21 minutes and 15 seconds

I don't think I can use strptime, since I'm working with the difference of two epoch dates. I could write something to do this, but I'm quite sure that there's something already written that I could use.

What module would be appropriate? Am I just missing something in time? My journey into Python is just really beginning, if this is indeed a duplicate it's because I failed to figure out what to search for.

Addendum

For accuracy, I really care most about the current year's calendar.

8 Answers

Check out the humanize package

https://github.com/jmoiron/humanize

import datetime

humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=1))

'a second ago'

humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600))

'an hour ago'

Here's a shorter one for interval in seconds and within a day (t<86400). Useful if you work with unix timestamps (seconds since epoch, UTC).

t = 45678
print('%d hours, %d minutes, %d seconds' % (t//3600, t%3600//60, t%60))

May be extended further (t//86400, ...).

A very old question but I found this solution which seems to be very simple in Python3:

print(datetime.timedelta(seconds=3600))
# output: 1:00:00
print(datetime.timedelta(hours=360.1245))
# output: 15 days, 0:07:28.200000
Related