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.
Example of use:
Advantage (You don't need third parties!).
Improved from "Liudmil Mitev" algorithm. (Thanks!)
Old question, but I personally like this approach most:
If you want to separate the seconds part with an "and" do:
A little improvement over @Schnouki's solution with a single line list comprehension. Also displays the plural in case of plural entities (like hours)
Import relativedelta
A lambda function
Example usage:
I had that exact same problem earlier today and I couldn't find anything in the standard libraries that I could use, so this is what I wrote:
humanize_time.py
You can use
dateutil.relativedelta()
to calculate the accurate time delta and humanize it with this script.You can use the wonderful dateutil module and its relativedelta class:
It doesn't count weeks, but that shouldn't be too hard to add.
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).
May be extended further (t//86400, ...).