Flo
Flo

Reputation: 1387

Python timedelta in full days, full hours and so on

I want some how to print a message like: "Since then, x days, y hours, z minutes and w seconds have elapsed". Currently I'm doing something like this but I miss the remainders plus (most importantly) I don't like it. There should be something more beautiful

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)

Upvotes: 2

Views: 3859

Answers (4)

nigel222
nigel222

Reputation: 8212

This may be deemed more beautiful, but I'm not sure it's actually pythonic. Personally I'd just hide away the "ugly" code in a function. Anyway,

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]

Upvotes: 1

niemmi
niemmi

Reputation: 17263

You can use 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))

Output:

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

Upvotes: 4

C14L
C14L

Reputation: 12558

There is Humanize to convert all sorts of data into human readable formats.

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

Upvotes: 2

Murali
Murali

Reputation: 1114

Try this, I hope this will be useful for you:

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)

Output:

0 year 10 month 0 days 11 hours 0 minutes   

Upvotes: 3

Related Questions