0

I have a list of string time stamps:

['08:29', '08:03', '00:00', '08:09', '08:13', '07:54', '07:30']

I want to convert each timestamp to decimal form, rounded to the nearest 0.5, and return the string. Output should be:

['8,5', '8,0', '0,0', '8,0', '8,0', '8,0', '7,5']

I have some ideas on how to do this but they are all messy on my head and I'm sure there's a function that I don't know that will help, numbers should be rounded between 0 and 5 decimals, so 7:46 would be 8.0, 7:35 would be 7,5 and so on...

maurera
  • 1,519
  • 1
  • 15
  • 28
user3577419
  • 77
  • 1
  • 7

4 Answers4

0

There are a few steps to this:

  1. Convert your string time to a datetime object
  2. Extract hours as a decimal
  3. Round this to the nearest 0.5
  4. Convert the number to string and replace decimal points with commas
from datetime import datetime
string_times = ['08:29', '08:03', '00:00', '08:09', '08:13', '07:54', '07:30']
numeric_times = []
for s in string_times:
    string_time = datetime.strptime(s, '%H:%M').time()
    numeric_time = string_time.hour+string_time.minute/60
    numeric_time_rounded = round(numeric_time*2)/2
    numeric_times.append(round(numeric_time_rounded,1))
output = [str(x).replace('.',',') for x in numeric_times]
print(output)

Output:

['8,5', '8,0', '0,0', '8,0', '8,0', '8,0', '7,5']
maurera
  • 1,519
  • 1
  • 15
  • 28
0

There isn't a build-in function. If you wanted to make a command that converts the time into a float, you fist must split the hours and minutes with string.split(":"). Then you can simply do hours+(minutes/60)

Here's the code:

time=['08:29', '08:03', '00:00', '08:09', '08:13', '07:54', '07:30']

def convert(clock_time):
    times = clock_time.split(":")
    hour=int(times[0])
    minutes=int(times[1])

    minutes=(minutes/60)

    if 0.25<minutes<0.75:
        minutes=0.5
    elif 0.75<minutes<1:
        minutes=1
    else:
        minutes=0
    newtime = hour+minutes

    return newtime
for i in range(len(time)):
    print(convert(time[i]))
-1

This function should work.

def conv(s):
    h, m = s.split(':', maxsplit=2)
    h = int(h)
    m = round(int(m) / 60 * 2) / 2
    if m >= 1:
        h += m // 1
        m %= 1

    return h + m

print(conv('07:44'))
print(conv('07:45'))
print(conv('07:46'))

output:

7.5
8.0
8.0
-1

Doesn't look great because I created this on my phone, but it should work

times = ['07:46', '07:35', '08:29', '08:03', '00:00', '08:09', '08:13'] 
new_times = [] 

for time in times:
    hours, minutes = time.split(":")
    minutes = round((int(minutes) / 60) * 2) / 2
    time = int(hours) + minutes
    new_times.append(str(time)) 
Frank
  • 93
  • 9