0

I need a way to detect that there's a time in a string with a xx:xx format, extract that time, plug it into a url and then replace that time with a markdown hyperlink to the url.

So for example if the string contains '... 19:30 ...', I want to replace it with '[19:30](https://www.thetimezoneconverter.com/?t={hour}%3A{min}&tz=GMT%2B1&)' in the string. At the moment I'm using this loop to forcibly get the time, but I have no way to refer to the original time in the string, so I can replace it:

import time

field_entry = 'blah blah blah, event at 19:30, be there'

for element in field_entry.split():
    try:
        time_for_url = time.strptime(element, '%H:%M')
    except:
        pass

print(f'https://www.thetimezoneconverter.com/?t={time_for_url.tm_hour}%3A{time_for_url.tm_min}&tz=GMT%2B1&')

As usual I'm probably thinking about this the wrong way and over-complicating it, so I'd love to see a different route.

2
  • Once you parse the time you should be able to access its different components, have you checked the docs?
    – AMC
    Commented Aug 7, 2020 at 0:38
  • Access the original time as seen in the url at the bottom, yes, but I had no way to refer to the time in the original string so I could replace it. Thankfully Don Foumare's answer is just what I needed.
    – user14062742
    Commented Aug 7, 2020 at 20:55

1 Answer 1

1

I had to update my answer again after I realized that you may want to replace multiple timestamps at once.

import re

field_entry = 'blah 18:36 blah blah, event at 19:30, be there'

def replace(match):
    hh, mm = match.group().split(':')
    return f'[{hh}:{mm}](https://www.thetimezoneconverter.com/?t={hh}%3A{mm}&tz=GMT%2B1&)'

field_entry = re.sub(r'(\d\d:\d\d)', replace, source, flags=re.DOTALL)

print(field_entry)
# Output:
# blah [18:36](https://www.thetimezoneconverter.com/?t=18%3A36&tz=GMT%2B1&) blah blah, event at [19:30](https://www.thetimezoneconverter.com/?t=19%3A30&tz=GMT%2B1&), be there

For more information see the docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.