如何在使用Python减去两个UNIX时间戳时产生可读的差异? [英] How can I produce a human readable difference when subtracting two UNIX timestamps using Python?

查看:182
本文介绍了如何在使用Python减去两个UNIX时间戳时产生可读的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题类似于这个关于用Python减去日期的问题,但不是相同。我不处理字符串,我必须弄清楚两个时代的时间戳之间的差异,并以人们可读的格式产生差异。

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.

例如: p>

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

我不认为我可以使用 strptime 米工作与两个时代的差异日期。我可以写一些东西来做到这一点,但我确信已经写了一些我可以使用的东西。

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.

什么模块是合适的?我只是缺少时间的东西?我的Python入门只是真正的开始,如果这确实是一个重复的,因为我没有找到什么要搜索。

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.

推荐答案

您可以使用精彩的 dateutil 模块及其

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.

这篇关于如何在使用Python减去两个UNIX时间戳时产生可读的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆