How to get the AM/PM indicator in Python

1 Answer

0 votes
import datetime

current_dt = datetime.datetime.now()
print(current_dt)

# Checks whether the current hour is greater than or equal to 12.
# If current_dt.hour >= 12 is True, it selects index 1 → "PM"
# If it's False, it selects index 0 → "AM"
print(['AM','PM'][current_dt.hour>=12]) 

dt = datetime.datetime(2025, 7, 9, 00, 5, 16, 156802)
print(dt)
print(['AM','PM'][dt.hour>=12])


'''
run:

2025-07-11 19:11:32.471150
PM
2025-07-09 00:05:16.156802
AM

'''

 



answered Jul 11, 2025 by avibootz
edited Jul 11, 2025 by avibootz
...