How can I convert int to time using datetime

Viewed 300

I have a list in this format:

L = [445, 650, 920, 1130, 1340]

results would be:

['4:45', '6:50', '9:20', '13:40']

I have tried this:

length = len(L)
L1 = str(L)
for i in range(length):
    tm = datetime.strptime(L1[i], '%H%M').time()
    print(tm)
4 Answers

That input is a bit odd, are you sure it's not decimal time e.g. 450 is 450mn (7h30), or 4.45h aka 4h27?

If you're sure the input is described properly, then you can just use divmod(n, 100) to split your time in two (the integral part from a division by 100, and the rest), then put the two values in the relevant field of a time or timedelta:

L = [445, 650, 920, 1130, 1340]
for v in L:
    h, m = divmod(v, 100)
    print(datetime.time(hour=h, minute=m))
04:45:00
06:50:00
09:20:00
11:30:00
13:40:00

It doesn't make sense as a datetime, a datetime must have the date part filled completely, although you could combine the time with a reference date to get a datetime.

You can do this with time class in datetime module. Use method strftime to convert time data into any str format that you want.

from datetime import time


def time_int_to_str(time_int):
    hour, minute = divmod(time_int, 100)
    t = time(hour=hour, minute=minute)
    time_str = t.strftime("%H:%M")
    return time_str[1:] if time_str[0] == "0" else time_str  # get rid of 0 at the start (e.g. 01:00 -> 1:00, and protection in case of 00:00)

With examples you have proivided:

L = [445, 650, 920, 1130, 1340]
[time_int_to_str(example) for example in L]

We receive:

['4:45', '6:50', '9:20', '11:30', '13:40']

You can try something like this:

get_time = lambda time: str(time)[:-2] + ':' + str(time)[-2:]
list(map(get_time,L))

['4:45', '6:50', '9:20', '11:30', '13:40']

from datetime import datetime
get_time = lambda time: datetime.strptime(str(time)[:-2] + ':' + str(time)[-2:], '%H:%M').time()
res = list(map(get_time,L))
res

[datetime.time(4, 45),
 datetime.time(6, 50),
 datetime.time(9, 20),
 datetime.time(11, 30),
 datetime.time(13, 40)]

comprehension

[ str(item)[:len(str(item)) - 2] + ':' + str(item)[len(str(item)) - 2:] for item in L  ]

['4:45', '6:50', '9:20', '11:30', '13:40']

Related