Alexis
Alexis

Reputation: 2294

Convert time interval string to time in python

I have the following string list:

my_list = ['10:00AM-12:00PM','12:30PM-03:00PM']

And I want to convert those strings to time interval (the difference of time in format hh:mm), in this case:

intervals = [02:00,01:30]

I have tried this:

import time

le_vals = []
for i, val in enumerate(intervals):
   le_vals.append(val.replace('-', ' ').split(' '))

the_diff = []
for i, val in enumerate(le_vals):
   the_diff.append((time.strptime(val[1], '%I:%M%p') - time.strptime(val[0], '%I:%M%p'))

But I'm stuck on how the last part to get the differences on the list the_diff. Since I have been requested to provide a concise question, I advance my logic but please, could you help me?

Upvotes: 0

Views: 1035

Answers (1)

S.B
S.B

Reputation: 16476

Your did a good job, but the items in the intervals list, are not valid in python! (you need strings?) Why don't you store them as a timedelta object ?

from datetime import datetime

my_list = ['10:00AM-12:00PM', '12:30PM-03:00PM']

res = []
for item in my_list:
    d1, d2 = item.split('-')

    d1 = datetime.strptime(d1, '%I:%M%p')
    d2 = datetime.strptime(d2, '%I:%M%p')
    res.append(d2 - d1)

print(res)

output :

[datetime.timedelta(seconds=7200), datetime.timedelta(seconds=9000)]

When you subtract two datetime objects from each other, timedelta object is created which has days and seconds property directly:

for i in res:
    print(i.days, i.seconds)

output:

0 7200
0 9000

If you need that string representation in question, either use str() on timedelta object(It shows seconds as well but with no zero padding hours) :

res = []
for item in my_list:
    d1, d2 = item.split('-')

    d1 = datetime.strptime(d1, '%I:%M%p')
    d2 = datetime.strptime(d2, '%I:%M%p')
    res.append(str(d2 - d1))  # <--------------- Here

print(res)

output :

['2:00:00', '2:30:00']

Or build it yourself to get the exact desired result, Here is a complete code:

from datetime import datetime

my_list = ['10:00AM-12:00PM', '12:30PM-03:00PM']

res = []
for item in my_list:
    d1, d2 = item.split('-')

    d1 = datetime.strptime(d1, '%I:%M%p')
    d2 = datetime.strptime(d2, '%I:%M%p')
    delta = d2 - d1

    m, s = divmod(delta.seconds, 60)
    h, m = divmod(m, 60)

    res.append(f'{h:02}:{m:02}')

print(res)

output:

['02:00', '02:30']

Upvotes: 4

Related Questions