0% found this document useful (0 votes)
13 views

Validate Time String Format

Uploaded by

Elliot Lassey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Validate Time String Format

Uploaded by

Elliot Lassey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Validate Time String Format

how do I make sure that a string is off the format 00:00:00 to 23:59:59

To ensure that a string is in the format `HH:MM:SS` where `HH` ranges from `00` to `23`, `MM` ranges
from `00` to `59`, and `SS` ranges from `00` to `59`, you can use regular expressions in Python. Here
is a step-by-step guide on how to do this:

1. Define a regular expression pattern that matches the desired format.


2. Use the `re` module to match the string against the pattern.

Here is a code example to illustrate this:

python

import re

def is_valid_time_string(time_str):
# Define the regular expression pattern
pattern = r"^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$"

# Match the string against the pattern


match = re.match(pattern, time_str)

# Return True if the string matches the pattern, False otherwise


return bool(match)

# Test cases
test_strings = ["00:00:00", "23:59:59", "12:34:56", "24:00:00", "23:60:00", "23:59:60", "1
2:34", "123456"]

for ts in test_strings:
print(f"{ts}: {is_valid_time_string(ts)}")

Explanation

1. Pattern Explanation:
`^(?:[01]\d|2[0-3])`: This part of the pattern ensures that the hour is between `00` and
`23`.
matches `00` to `19`.
`[01]\d`
matches `20` to `23`.
`2[0-3]`
`:[0-5]\d`: This part ensures that the minutes are between `00` and `59`.
`[0-5]` matches the first digit (0-5).
`\d` matches any digit (0-9).
`:[0-5]\d$`: This part ensures that the seconds are between `00` and `59`, similar to the
minutes.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/2
2. Using `re.match`:
The `re.match` function checks if the entire string matches the pattern. If it does, it returns
a match object; otherwise, it returns `None`.

3. Test Cases:
The code includes a few test cases to demonstrate the function's usage and validity.

This method ensures that the time string strictly adheres to the `HH:MM:SS` format within the specified
ranges.
ChatGPT can make mistakes. Check important info.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/2

You might also like