'Using regular expression for reformatting a time

I am looking to automate ingesting some data but the format of the time I've scraped for each row is different to what I need.

The data I scrape comes like this

  • 9a.m.–5p.m.
  • Open 24 hours

It should look like the below:

  • 09:00AM,05:00AM
  • {empty}

So far I have the below that only works for the second attribute, I'm struggling with the time reformatting and doing it in the same regex.

[str_replace(array("Open 24 Hours"),array(""),{import_element[1]})]

I would appreciate any help.

Thanks



Solution 1:[1]

Assuming your data has just hours (not minutes in the input string), this should work:

import re

def process_match(m):
    n = m[:-4]
    AmPm = m[-4:].replace(".", "").upper()
    if len(n) == 1:
        res = f"0{n}:00{AmPm}"
    else:
        res = f"{n}:00{AmPm}"
    return res
    

inpt = "9a.m.–5p.m."
matches = re.findall(r"\d[ap].m.", inpt)

print(f"{process_match(matches[0])},{process_match(matches[1])}")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rikyeah