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

查看:20
本文介绍了使用 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.

例如:

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.

什么模块合适?我只是在 time 中遗漏了什么吗?我的 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模块及其 relativedelta 类:

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天全站免登陆