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.
For accuracy, I really care most about the current year's calendar.
You can use the wonderful dateutil module and its relativedelta class:
import datetime
import dateutil.relativedelta
dt1 = datetime.datetime.fromtimestamp(123456789) # 1973-11-29 22:33:09
dt2 = datetime.datetime.fromtimestamp(234567890) # 1977-06-07 23:44:50
rd = dateutil.relativedelta.relativedelta (dt2, dt1)
print "%d years, %d months, %d days, %d hours, %d minutes and %d seconds" % (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds)
# 3 years, 6 months, 9 days, 1 hours, 11 minutes and 41 seconds
It doesn't count weeks, but that shouldn't be too hard to add.