Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Format time in AM-PM format
In Python, we can format time in AM/PM (12-hour) format using built-in functions like strftime() and datetime.now(). The AM/PM format is commonly used in user interfaces, reports, documents, data visualization, and event scheduling. AM represents time from midnight (00:00) to 11:59, while PM represents time from noon (12:00) to 11:59 PM.
Syntax
The basic syntax for formatting time in AM/PM format is ?
strftime('%I:%M:%S %p')
The strftime() function uses format codes to represent different time components:
%I ? Hours in 12-hour format (01-12)
%M ? Minutes (00-59)
%S ? Seconds (00-59)
%p ? AM/PM indicator
Converting 24-Hour Format to AM/PM
This example converts a time string from 24-hour format to 12-hour AM/PM format ?
from datetime import datetime
t_str = '22:45:32'
t_obj = datetime.strptime(t_str, '%H:%M:%S')
# Convert to AM/PM format
t_am_pm = t_obj.strftime('%I:%M:%S %p')
print("The given time:", t_str)
print("The format in (AM/PM):", t_am_pm)
The given time: 22:45:32 The format in (AM/PM): 10:45:32 PM
Getting Current Time in AM/PM Format
This example displays the current time in AM/PM format ?
from datetime import datetime
dt_obj = datetime.now()
ts_am_pm = dt_obj.strftime('%I:%M:%S %p')
print("The current time:", dt_obj)
print("The format in (AM/PM):", ts_am_pm)
The current time: 2023-04-18 17:50:01.963742 The format in (AM/PM): 05:50:01 PM
Using a Function for Time Formatting
This example creates a reusable function to format time in AM/PM format ?
from datetime import datetime
def format_time(time_obj):
return time_obj.strftime('%I:%M %p')
current_time = datetime.now()
formatted_time = format_time(current_time)
print("Time in AM/PM:", formatted_time)
Time in AM/PM: 06:04 PM
Using the time Module
This example uses the time module to format the current time in AM/PM format ?
import time
present_time = time.localtime()
t_format = time.strftime("%I:%M %p", present_time)
print("Current time in AM/PM:", t_format)
Current time in AM/PM: 06:18 PM
Format Code Comparison
| Format Code | Description | Example Output |
|---|---|---|
%I |
12-hour format (01-12) | 01, 02, ... 12 |
%H |
24-hour format (00-23) | 00, 01, ... 23 |
%M |
Minutes (00-59) | 00, 30, 59 |
%p |
AM/PM indicator | AM, PM |
Conclusion
Python's strftime() function makes it easy to format time in AM/PM format using format codes like %I, %M, %S, and %p. You can use either the datetime or time module depending on your specific needs.
