且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Python 减去两个 UNIX 时间戳时,如何产生人类可读的差异?

更新时间:2022-12-18 11:04:28

你可以使用精彩的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.