Python timedelta全天,全天等等

时间:2016-04-28 08:55:35

标签: python datetime timedelta

我想要一些如何打印消息: “从那以后,x天,y小时,z分钟和w秒已经过去了”。 目前我正在做这样的事情,但我想念剩余的人(最重要的是)我不喜欢它。应该有更美丽的东西

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)

4 个答案:

答案 0 :(得分:3)

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

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   

答案 1 :(得分:3)

您可以使用timedelta

<input type="text" ng-model="search" ... >

<md-grid-tile ng-repeat="items in tabsCtrl.countProducts track by $index" | filter : search ...

输出:

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))

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

这可能被认为更美,但我不确定它实际上是pythonic。就个人而言,我只是隐藏了一个函数中的“丑陋”代码。无论如何,

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]