0

Is there a way to check if a time (represented as string) is in the format 'HH:MMa' or 'HH:MMp'?

For example, '12:30p', '11:30a', or '8:30p' could be an input time (where a = am, p = pm).

Thanks!

swing1234
  • 233
  • 1
  • 3
  • 13
  • ``"12:30p".endswith("p")`` or ``"12:30p".endswith("a")`` incase of string – sushanth Jul 24 '20 at 16:06
  • Is the time in a string or a datetime or time data type? – Ben Jul 24 '20 at 16:06
  • Can you give more details on what you want? Do u just want to differentiate between am and pm? – Raz Crimson Jul 24 '20 at 16:08
  • If the time is a string you can check the last charachter of the string. You can access it by doing ```str[::-1]``` where is ```str``` is the string containing the time. – Andrej Jul 24 '20 at 16:08
  • Edited my post. The input string is like the one mentioned and I want to check if it is in the format HH:MMa or HH:MMp – swing1234 Jul 24 '20 at 16:09
  • Do you want to know if the time is valid? For example if hour is less than 24 and the minutes less than 60? – Andrej Jul 24 '20 at 16:11
  • You just want to check if its in that format, or do you need to make a datetime object of it? – Raz Crimson Jul 24 '20 at 16:12
  • No, I just want to check if the input string is in the format HH:MMa or HH:MMp. Something like this (https://stackoverflow.com/questions/1322464/python-time-format-check) but instead we are checking if the last character is either and a or p. – swing1234 Jul 24 '20 at 16:13
  • You can do ```str = "HH:MMp" if str[::-1] == "a": return "a" elif str[::-1] == "a": return "b"``` – Andrej Jul 24 '20 at 16:20

2 Answers2

1
timestring = "11:30a"
import re
pattern = re.compile("^(1[012]|[1-9]):[0-5][0-9][ap]$")
pattern.match(timestring)
javaDeveloper
  • 1,403
  • 3
  • 28
  • 42
0

A modified version of the code u linked me too

import time

def isTimeFormat(input):
    try:
        if input[-1] == 'a' or input[-1] == 'p':
            time.strptime(input[:-1], '%H:%M')
            return True
        else:
            return False
    except ValueError:
        return False
Raz Crimson
  • 187
  • 9