Sling Academy
Home/Python/Python: Convert 24h time format to AM/PM format (and vice versa)

Python: Convert 24h time format to AM/PM format (and vice versa)

Last updated: February 13, 2024

Overview

Handling time in programming often requires converting between different formats. A common task that you might encounter is converting between 24-hour (military) time format and 12-hour AM/PM time formats. Python, with its rich standard library, provides straightforward ways to perform these conversions. In this tutorial, we’ll explore how to accomplish these conversions effectively and accurately.

Understanding 24-hour and AM/PM Time Formats

In the 24-hour format, time is represented in a range from 00:00 to 23:59, where 00:00 is midnight and 23:59 is one minute before the next midnight. On the other hand, the 12-hour format divides the day into two periods, AM (ante meridiem, before midday) and PM (post meridiem, after midday), each ranging from 12:00 to 11:59. The 12-hour format often requires knowing the specific part of the day (AM or PM) to understand the actual time.

Making Use of Python’s datetime Module

Python’s datetime module allows us to work with dates and times with ease. Before delving into specific examples of conversion, it’s important to understand how to work with this module. We’ll start by importing it and creating a datetime object:

from datetime import datetime
# Creating a datetime object for 2:30 PM
now = datetime.strptime("14:30", "%H:%M")

This code snippet creates a datetime object representing 2:30 PM using the strptime method, which parses a time string according to a format specifier.

Converting 24-hour Time to 12-hour Time

Let’s convert a 24-hour format time into 12-hour AM/PM format:

formatted_time = now.strftime("%I:%M %p")
print(formatted_time)

This will output:
02:30 PM
The %I specifier represents the hour in 12-hour format, while %p adds the AM/PM indicator.

Converting 12-hour Time to 24-hour Time

Converting from the 12-hour format to 24-hour format is just as straightforward:

# Assuming a time in 12-hour format
input_time = "02:30 PM"
# Converting to 24-hour format
converted_time = datetime.strptime(input_time, "%I:%M %p").strftime("%H:%M")
print(converted_time)

This will output:
14:30
Here, we use %H for the hour in 24-hour format.

Handling Edge Cases and Common Pitfalls

When working with time conversion, it’s important to handle edge cases like midnight (00:00 in 24-hour format, which is 12:00 AM in 12-hour format) and noon (12:00 PM in both formats). Properly understanding and applying the format specifiers ensures accuracy across various scenarios. Be mindful of cases where input times might not strictly follow expected patterns, leading to parsing errors. It’s also advisable to encapsulate the conversion logic within functions to promote code reuse and readability.

Let’s define a pair of functions for our conversions:

def convert_to_am_pm(time_str):
    return datetime.strptime(time_str, "%H:%M").strftime("%I:%M %p")

def convert_to_24h(time_str):
    return datetime.strptime(time_str, "%I:%M %p").strftime("%H:%M")

These functions enhance modularity and simplify conversion tasks within your Python projects.

Dealing with User Input

When dealing with user input, it’s crucial to validate the input time string for correctness and to correctly handle exceptions. Python’s datetime module throws a ValueError exception if the input doesn’t match the expected format. Here’s how to gracefully handle such situations:

try:
    user_input = input("Enter time (HH:MM format): ")
    print(convert_to_am_pm(user_input))
except ValueError:
    print("Invalid time format. Please try again.")

This approach ensures that your program remains user-friendly and robust against invalid input.

Summary

In this tutorial, we’ve covered the essentials of converting between 24-hour and 12-hour AM/PM time formats in Python. By leveraging the datetime module and understanding the relevant format specifiers, you can handle time conversions effortlessly. We also explored handling edge cases, improving code modularity through functions, and ensuring user input is correctly processed. With these skills, you’re well-equipped to incorporate time format conversions in your Python applications, enhancing their functionality and user experience.

Next Article: Python: How to get only date part from a datetime object

Previous Article: Python: How to Convert a Date String to a Timestamp

Series: Date and Time in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types