How to Solve Time Conversion Problems in Python?

Estimated read time 3 min read

Time conversion refers to converting a time in one format to another format. For instance, converting a time from the 12-hour format to the 24-hour format. Here are some examples of how to solve time conversion problems in Python:

  1. Converting a time from the 12-hour format to the 24-hour format:
def convert_time_12_to_24(time_12):
    """
    Convert a time from the 12-hour format to the 24-hour format.
    """
    # Split the time string into hours, minutes, and period
    hours, minutes_period = time_12.split(':')
    minutes, period = minutes_period.split()
    
    # Convert the hours to an integer
    hours = int(hours)
    
    # If the period is PM and the hours are not 12, add 12 to the hours
    if period == 'PM' and hours != 12:
        hours += 12
    
    # If the period is AM and the hours are 12, set the hours to 0
    elif period == 'AM' and hours == 12:
        hours = 0
    
    # Convert the hours and minutes to strings and pad them with zeros
    hours = str(hours).zfill(2)
    minutes = str(minutes).zfill(2)
    
    # Return the time in the 24-hour format
    return f"{hours}:{minutes}"

Example usage:

>>> convert_time_12_to_24('06:30 PM')
'18:30'
  1. Converting a time from the 24-hour format to the 12-hour format:
def convert_time_24_to_12(time_24):
    """
    Convert a time from the 24-hour format to the 12-hour format.
    """
    # Split the time string into hours and minutes
    hours, minutes = time_24.split(':')
    
    # Convert the hours to an integer
    hours = int(hours)
    
    # Determine the period (AM or PM)
    period = 'AM' if hours < 12 else 'PM'
    
    # Convert the hours to the 12-hour format
    hours = hours % 12
    if hours == 0:
        hours = 12
    
    # Convert the hours and minutes to strings and pad them with zeros
    hours = str(hours).zfill(2)
    minutes = str(minutes).zfill(2)
    
    # Return the time in the 12-hour format
    return f"{hours}:{minutes} {period}"

Example usage:

>>> convert_time_24_to_12('18:30')
'06:30 PM'
  1. Converting a duration in seconds to a string in the format “HH:MM:SS”:
def convert_seconds_to_duration(seconds):
    """
    Convert a duration in seconds to a string in the format "HH:MM:SS".
    """
    # Calculate the hours, minutes, and seconds
    hours = seconds // 3600
    minutes = (seconds % 3600) // 60
    seconds = seconds % 60
    
    # Convert the hours, minutes, and seconds to strings and pad them with zeros
    hours = str(hours).zfill(2)
    minutes = str(minutes).zfill(2)
    seconds = str(seconds).zfill(2)
    
    # Return the duration as a string in the format "HH:MM:SS"
    return f"{hours}:{minutes}:{seconds}"

Example usage:

>>> convert_seconds_to_duration(3661)
'01:01:01'

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply