How to format a date using different formats in Python

1 Answer

0 votes
from datetime import datetime

# strftime() converts a datetime object into a 
# string using format codes like %Y, %m, %d

# Get current date and time
now = datetime.now()

print("Original datetime object:", now, "\n")

# Year formats
print("Year (4 digits):", now.strftime("%Y"))     
print("Year (2 digits):", now.strftime("%y"))      

# Month formats
print("Month (01-12):", now.strftime("%m"))         
print("Month name (short):", now.strftime("%b"))   
print("Month name (full):", now.strftime("%B"))     

# Day formats
print("Day of month:", now.strftime("%d"))          
print("Day of week (short):", now.strftime("%a"))   
print("Day of week (full):", now.strftime("%A"))    

# Combined common formats
print("YYYY-MM-DD:", now.strftime("%Y-%m-%d"))    
print("DD/MM/YYYY:", now.strftime("%d/%m/%Y"))     
print("MM-DD-YYYY:", now.strftime("%m-%d-%Y"))      

# Time formats
print("24-hour time:", now.strftime("%H:%M:%S"))    
print("12-hour time:", now.strftime("%I:%M %p"))    

# Full datetime formats
print("ISO-like:", now.strftime("%Y-%m-%d %H:%M:%S"))        
print("Readable:", now.strftime("%A, %B %d, %Y %I:%M %p"))   

# Misc formats
print("Week number:", now.strftime("%U"))             
print("Day of year:", now.strftime("%j"))             
print("Locale date:", now.strftime("%x"))            
print("Locale time:", now.strftime("%X"))            



'''
run:

Original datetime object: 2026-05-20 15:25:09.532608 

Year (4 digits): 2026
Year (2 digits): 26
Month (01-12): 05
Month name (short): May
Month name (full): May
Day of month: 20
Day of week (short): Wed
Day of week (full): Wednesday
YYYY-MM-DD: 2026-05-20
DD/MM/YYYY: 20/05/2026
MM-DD-YYYY: 05-20-2026
24-hour time: 15:25:09
12-hour time: 03:25 PM
ISO-like: 2026-05-20 15:25:09
Readable: Wednesday, May 20, 2026 03:25 PM
Week number: 20
Day of year: 140
Locale date: 05/20/26
Locale time: 15:25:09

'''

 



answered 7 hours ago by avibootz
...