0

I am trying to check if a given time is valid, using any of python's multiple datetime libraries. This given time would be in 24hr format, and examples of valid inputs are 2359, 0000, 1330, while examples of invalid inputs would be 2400, 2360, 2500.

May I ask if there is a better way to check the validity of the input, without parsing through the strings to check individually?

Preferably using python libraries, if possible

If there are no such libraries, may I instead ask how this should be done in regex?

martineau
  • 119,623
  • 25
  • 170
  • 301
miloovann
  • 21
  • 6

5 Answers5

3

You can attempt to parse it using time.strptime:

import time

def is_valid_time(value):
    try:
        _ = time.strptime(value, '%H%M')
    except ValueError:
        return False

    return True
chash
  • 3,975
  • 13
  • 29
3

You can use strptime for parsing, with format %H%M. If it fails, it is invalid.

from datetime import datetime

try:
    datetime.strptime('2359', '%H%M')
    print('valid')
except ValueError:
    print('invalid')
shx2
  • 61,779
  • 13
  • 130
  • 153
3

Why do you need a library? You could do it with bare Python code:

STRTIME = "2317"

if (0 <= int(STRTIME[:2]) < 24 and 0 <= int(STRTIME[2:]) < 60):
   print("Valid")
chepner
  • 497,756
  • 71
  • 530
  • 681
panadestein
  • 1,241
  • 10
  • 21
  • 1
    what about STRTIME='199'? I would argue you shouldn't try to write parsing code yourself, when a standard one already exists. – shx2 Jun 02 '20 at 17:41
  • Then you could check the length of the string. It looks simple and readable to me. – panadestein Jun 02 '20 at 18:11
  • 1
    @shx2: on the other hand, one could argue that `strptime` is overkill for this task. Also, applied thousands of times, it would make the code painfully slow, given that it is used only for a simple check like this. – FObersteiner Jun 02 '20 at 18:23
1

Regex approach need to be added in your date time scenario

^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$ (js engine)

Logic:

  • The first number (hours) is either: a number between 0 and 19 --> [0-1]?[0-9] (allowing single digit number) or a number between 20 - 23 --> 2[0-3]
  • the second number (minutes) is always a number between 00 and 59 --> [0-5][0-9] (not allowing a single digit)
Pallav Chanana
  • 617
  • 5
  • 10
1

You might get along with a regular expression:

\b(?:[01][0-9]|2[0-3])[0-5][0-9]\b

See a demo on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79