Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

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
...