Working (CS50P)

24H Time Conversion

Description:

Python utility that transforms 12-hour to 24-hour time formats, using regex for accuracy. Ideal for scheduling systems and data processing, it supports different time expressions, ensures precise conversions, and robustly handles format variations and potential errors, streamlining time-related data management tasks.

Objectives:

  • To create a function convert that takes a string in 12-hour format and returns it in 24-hour format.
  • To handle both simple (hour-only) and complex (hour and minute) time formats.
  • To implement error handling for invalid time formats or values.

Detail:

Main program:

  • Regular Expressions for Input Validation: Utilized regular expressions (re module) to ensure the input conforms to expected time formats, either with or without minutes. This approach guarantees that the program only processes valid time formats, enhancing its reliability.
    if matches := re.search(r"^(\d+) (AM|PM) to (\d+) (AM|PM)$", s, re.IGNORECASE):
        # ... (time conversion logic)
    
  • Conditional Logic for Time Conversion: Implemented conditional logic to accurately handle different cases in time conversion, such as distinguishing between AM and PM and handling special cases like ’12 AM’ and ’12 PM’.
    if start_daytime == 'AM':
        if start_hour == '12':
            start_hour = 0
        else:
            start_hour = int(start_hour)
    # ... (further conversion logic)
    
  • Error Handling: Incorporated error handling to raise ValueError for inputs that don’t match the expected format or contain invalid time values (like ‘9:60 AM’). This robust error checking prevents incorrect or ambiguous inputs from causing erroneous conversions.
  • Modular Design: The code is structured into functions, with main() handling user interaction and convert() performing the core conversion logic. This modular design enhances readability, maintainability, and potential for reuse in larger applications.

Unit testing:

  • Unit Testing with Pytest: Developed test_working.py, employing the pytest framework to conduct unit tests. These tests cover a range of scenarios, including simple and complex time formats and error-raising cases, ensuring the program’s accuracy and reliability.
  • Test Cases: Test cases are designed to validate both standard and edge-case scenarios. For instance, tests for ‘8:35 AM to 2:30 PM’ and ’10:15 PM to 05 AM’ ensure the program handles minutes correctly, while tests with invalid formats rigorously check the program’s error handling capabilities.
Explore details

Project Status:

Completed

Data sources:

Problem Set 7 from Harvard’s CS50P 2023.

Full Overview