How can I produce a human readable difference when subtracting two UNIX timestamps using Python?(使用 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 时间戳时,如何产生人类可读的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Python 减去两个 UNIX 时间戳时,如何产生人类
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 沿轴计算直方图 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
