Python 全天、全小时等的时间增量

Python timedelta in full days, full hours and so on

我想了解如何打印消息,例如: "Since then, x days, y hours, z minutes and w seconds have elapsed"。 目前我正在做这样的事情,但我想念剩下的部分(最重要的是)我不喜欢它。应该有更美的

dt = (datetime.now() - datetime(year=1980, month=1, day=1, hour=18)).total_seconds()
full_days = int(dt // (3600 * 24))
full_hours = int((dt - full_days * (24 * 3600)) // 3600)
full_minutes = int((dt - full_days * (24 * 3600) - full_hours * 3600) // 60)
residual_seconds = dt - full_days * (24 * 3600) - full_hours * 3600 - full_minutes * 60
print(full_days, full_hours, full_minutes, residual_seconds)

试试这个,希望对你有用:

import datetime
from dateutil.relativedelta import relativedelta

end = '2016-01-01 12:00:00'
begin = '2015-03-01 01:00:00'

start = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(begin, '%Y-%m-%d %H:%M:%S')

diff = relativedelta(start, ends)

print "%d year %d month %d days %d hours %d minutes" % (diff.years, diff.months, diff.days, diff.hours, diff.minutes)

输出:

0 year 10 month 0 days 11 hours 0 minutes   

Humanize 可以将各种数据转换为人类可读的格式。

>>> import humanize
>>> from datetime import datetime, timedelta
>>> humanize.naturaltime(datetime.now() - timedelta(seconds=3600))
'an hour ago'

您可以使用 timedelta:

from datetime import datetime

fmt = 'Since then, {0} days, {1} hours, {2} minutes and {3} seconds have elapsed'
td = datetime.now() - datetime(year=1980, month=1, day=1, hour=18)
print(fmt.format(td.days, td.seconds // 3600, td.seconds % 3600 // 60, td.seconds % 60))

输出:

Since then, 13266 days, 23 hours, 5 minutes and 55 seconds have elapsed

这可能被认为更漂亮,但我不确定它是否真的是 pythonic。就我个人而言,我只是将 "ugly" 代码隐藏在一个函数中。总之,

dt=datetime(2016,1,2,11,30,50)-datetime(2016,1,1)

s=dt.total_seconds()

t=[]
for x in (24*3600,3600,60,1):
   t.append(s//x)
   s -= t[-1]*x

days,hours,mins,secs=t

>>> print(t)
[1.0, 11.0, 30.0, 50.0]