Home > Software engineering >  How to convert the following time format to a time formatted string (HH:MM:SS)
How to convert the following time format to a time formatted string (HH:MM:SS)

Time:12-28

I am reading the following kind of data from a file. The time is written like this there:

Forat of time I wish to convert

Is there a way I can convert the above string to the format 'HH:MM:SS'.I do not want a time object. It should return me a string.

I tried stripping the letters H and M but some data fields do not have H specified with them, so I could not figure out any other way to solve this problem.

Any help is welcome.

CodePudding user response:

Your approach is totally fine:

  1. strip H and M
  2. convert to time 100 (int())
  3. get the hours by dividing by 100 (// integer division)
  4. get the minutes modulo 100 (%)
  5. format the output using an f-string (f"") and 2 places with leading zeros (:02)
time = int("5M".replace("H", "").replace("M", ""))
print(f"{time//100:02}:{time0:02}:00")

Maybe a more verbose implementation helps you understanding it. It also provides the output of all the cases you listed:

for inp in ["24H45M", "4H25M", "35M", "24H20M", "50M", "2H20M", "38M", "1H20M"]:
    stripped = inp.replace("H", "").replace("M", "")
    time100 = int(stripped)
    hours = time100 // 100
    minutes = time100 % 100
    print(f"{hours:02}:{minutes:02}:00")

CodePudding user response:

instr = "24H45M"

hour = "00"
minute = "00"
second = "00"
arr = list(instr)
start = 0

for i, char in enumerate(arr):
    if char == "H":
        hour = int(''.join(arr[start:i]))
        start=i 1
    if char == "M":
        minute = int(''.join(arr[start:i]))
        start=i 1
    if char == "S":
        second = int(''.join(arr[start:i]))
        start=i 1

print(f"{hour}:{minute}:{second}")

CodePudding user response:

You could do it like this:

from datetime import datetime
try:
    print(datetime.strptime("10H5M", "%HH%MM").strftime("%H:%M:%S"))
except ValueError:
    try:
        print(datetime.strptime("10H", "%HH").strftime("%H:%M:%S"))
    except ValueError:
        print(datetime.strptime("5M", "%MM").strftime("%H:%M:%S"))

view the formatting here, you could also use the str.find method instead of using try and except. Note the find method return -1 if not found and 0 if found so it would look something like:

from datetime import datetime
time_str = "10H5M"
if (time_str.find("H")   1):
    if (time_str.find("M")   1):
        print(datetime.strptime("10H5M", "%HH%MM").strftime("%H:%M:%S"))
    else:
        print(datetime.strptime("10H", "%HH").strftime("%H:%M:%S"))
else:
    print(datetime.strptime("5M", "%MM").strftime("%H:%M:%S"))

CodePudding user response:

You can user re.search to extract numbers and str.zfill to add leading zeroes

import re


def format_time(s):
    hours = 0
    m = re.search(r'(\d )H', s)
    if m:
        hours = m.group(1)

    minutes = 0
    m = re.search(r'(\d )M', s)
    if m:
        minutes = m.group(1)

    seconds = 0
    m = re.search(r'(\d )S', s)
    if m:
        seconds = m.group(1)

    return f"{str(hours).zfill(2)}:{str(minutes).zfill(2)}:{str(seconds).zfill(2)}"


print(format_time("24H45M"))
print(format_time("35M"))
print(format_time("15M16S"))
  • Related