How to format time only in Python

1 Answer

0 votes
from datetime import datetime, timezone, timedelta

def show(label, pattern, dt):
    print(f"{label.ljust(30)} {pattern.ljust(15)} → {dt.strftime(pattern)}")

print("\n=== Python Time Formatting Examples ===\n")

# Current time (naive)
now = datetime.now()

# Current time with timezone (+03:00 example)
now_tz = datetime.now(timezone(timedelta(hours=3)))

print(f"Current local datetime:      {now}")
print(f"Current datetime with TZ:    {now_tz}")
print("-" * 60)

# --- 24-HOUR FORMATS ---
show("24-hour HH:MM:SS", "%H:%M:%S", now)
show("24-hour HH:MM", "%H:%M", now)
show("24-hour with microseconds", "%H:%M:%S.%f", now)

# --- 12-HOUR FORMATS ---
show("12-hour hh:MM:SS AM/PM", "%I:%M:%S %p", now)
show("12-hour hh:MM AM/PM", "%I:%M %p", now)

# --- MILLISECONDS / MICROSECONDS ---
show("Microseconds", "%f", now)
print("Milliseconds                 %H:%M:%S.%f   →", now.strftime("%H:%M:%S.%f")[:-3])

# --- TIMEZONE FORMATS ---
show("Time with numeric offset", "%H:%M:%S %z", now_tz)
show("Time with timezone name", "%H:%M:%S %Z", now_tz)

# --- COMMON PATTERNS ---
show("HH:MM:SS (common)", "%H:%M:%S", now)
show("HH:MM (common)", "%H:%M", now)
show("hh:MM AM/PM", "%I:%M %p", now)
show("Time + microseconds", "%H:%M:%S.%f", now)



'''
run:

=== Python Time Formatting Examples ===

Current local datetime:      2026-05-21 05:40:35.183797
Current datetime with TZ:    2026-05-21 08:40:35.183805+03:00
------------------------------------------------------------
24-hour HH:MM:SS               %H:%M:%S        → 05:40:35
24-hour HH:MM                  %H:%M           → 05:40
24-hour with microseconds      %H:%M:%S.%f     → 05:40:35.183797
12-hour hh:MM:SS AM/PM         %I:%M:%S %p     → 05:40:35 AM
12-hour hh:MM AM/PM            %I:%M %p        → 05:40 AM
Microseconds                   %f              → 183797
Milliseconds                 %H:%M:%S.%f   → 05:40:35.183
Time with numeric offset       %H:%M:%S %z     → 08:40:35 +0300
Time with timezone name        %H:%M:%S %Z     → 08:40:35 UTC+03:00
HH:MM:SS (common)              %H:%M:%S        → 05:40:35
HH:MM (common)                 %H:%M           → 05:40
hh:MM AM/PM                    %I:%M %p        → 05:40 AM
Time + microseconds            %H:%M:%S.%f     → 05:40:35.183797
--------------------------------------------------

'''

 



answered 9 hours ago by avibootz

Related questions

...