From list of decimal to hours / minutes

Question:

I have a list like the following:

T = [10.749957462142994, 10.90579301143351, 10.981580990083001]

That contains timestamp in a decimal format

hours =  [ int(x) for x in T ]
minutes =[ (x*60) % 60 for x in T]

print("%d:%02d"%(hours[0], minutes[0]), "%d:%02d"%(hours[1], minutes[1]), "%d:%02d"%(hours[2], minutes[2]))
['10:44', '10:54', '10:58']

I would like to create a list of datetime without years-month-day but just hours and minutes.

I tried this:

from datetime import datetime
DT = []
for i,t in enumerate(T):
    string = str("%d:%02d"%(hours[i], minutes[i]))
    datetime_object = datetime. strptime(string, '%H:%M')
    DT.append(datetime_object)

However DT looks like the following:

DT
[datetime.datetime(1900, 1, 1, 10, 44),
 datetime.datetime(1900, 1, 1, 10, 54),
 datetime.datetime(1900, 1, 1, 10, 58)]

How can I remove the information of year, day and month and have something like:

DT
[datetime.datetime( 10, 44),
 datetime.datetime( 10, 54),
 datetime.datetime( 10, 58)]
Asked By: emax

||

Answers:

You can use datetime.time or if you really want to use datetime.datetime then you can get the time only with datatime.datetime.time() method.

Answered By: Prango

Here’s a simple way to do it:

import datetime

DUMMY_DATETIME = datetime.datetime(2000, 1, 1, 0, 0)
HOUR = datetime.timedelta(hours=1)

T = [10.749957462142994, 10.90579301143351, 10.981580990083001]
DT = [(DUMMY_DATETIME + hours * HOUR).time() for hours in T]

A timedelta can be multiplied by a float (automatically rounding to microseconds), which lets you easily convert a fractional hours value into a timedelta, without having to manually do the multiplication/division/modulo by 60.

The date part (Y2K) of the DUMMY_DATETIME object is just there to make the + operator work (because time + timedelta is a TypeError, but datetime + timedelta is fine). All that matters is the hours/minutes/seconds part being 0.

The expression DUMMY_DATETIME + hours * HOUR thus gives a timestamp that’s the specified number of hours after the epoch. And calling .time() on that object gives you the time, without the useless year/month/day part.

>>> DT
[datetime.time(10, 44, 59, 846864), datetime.time(10, 54, 20, 854841), datetime.time(10, 58, 53, 691564)]
>>> [t.strftime('%H:%M') for t in DT]
['10:44', '10:54', '10:58']
Answered By: dan04

I’ve taken a slightly different approach:

from datetime import time, datetime, timedelta
T = [10.749957462142994, 10.90579301143351, 10.981580990083001]
values = [(datetime.min + timedelta(hours=t)).time() for t in T]

timedelta objects support arbitrary floats for the hours. The result is a rather simple 1 line of code.

Answered By: Bharel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.