🎨 Formatting Dates and Times
Formatting dates and times for display is essential for user interfaces, reports, and data presentation. Python's strftime()
method provides powerful formatting capabilities using format codes to create exactly the display you need.
from datetime import datetime
now = datetime.now()
# Different formatting styles
print(f"ISO format: {now.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"US format: {now.strftime('%m/%d/%Y %I:%M %p')}")
print(f"Readable: {now.strftime('%B %d, %Y at %I:%M %p')}")
print(f"Short: {now.strftime('%b %d, %y')}")
🎯 Common Format Patterns
Different applications need different date formats. Here are the most common patterns.
Basic Date Formatting
from datetime import datetime
now = datetime.now()
# Year formats
print(f"4-digit year: {now.strftime('%Y')}")
print(f"2-digit year: {now.strftime('%y')}")
# Month formats
print(f"Month number: {now.strftime('%m')}")
print(f"Full month: {now.strftime('%B')}")
print(f"Short month: {now.strftime('%b')}")
# Day formats
print(f"Day of month: {now.strftime('%d')}")
print(f"Full weekday: {now.strftime('%A')}")
print(f"Short weekday: {now.strftime('%a')}")
Time Formatting
from datetime import datetime
now = datetime.now()
# 24-hour format
print(f"24-hour time: {now.strftime('%H:%M:%S')}")
print(f"Hour (24): {now.strftime('%H')}")
# 12-hour format
print(f"12-hour time: {now.strftime('%I:%M:%S %p')}")
print(f"Hour (12): {now.strftime('%I')}")
print(f"AM/PM: {now.strftime('%p')}")
# Minutes and seconds
print(f"Minutes: {now.strftime('%M')}")
print(f"Seconds: {now.strftime('%S')}")
Combined Date and Time
from datetime import datetime
now = datetime.now()
# Professional formats
print(f"Log format: {now.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Email format: {now.strftime('%a, %d %b %Y %H:%M:%S')}")
print(f"Human readable: {now.strftime('%A, %B %d, %Y at %I:%M %p')}")
# Compact formats
print(f"Compact: {now.strftime('%Y%m%d_%H%M%S')}")
print(f"File safe: {now.strftime('%Y-%m-%d_%H-%M-%S')}")
📊 Format Code Reference
Complete reference for Python's datetime format codes.
Date Format Codes
Code | Description | Example |
---|---|---|
%Y | 4-digit year | 2024 |
%y | 2-digit year | 24 |
%m | Month as number | 03 |
%B | Full month name | March |
%b | Abbreviated month | Mar |
%d | Day of month | 15 |
%A | Full weekday name | Friday |
%a | Abbreviated weekday | Fri |
%w | Weekday as number (0-6) | 5 |
%j | Day of year | 075 |
Time Format Codes
Code | Description | Example |
---|---|---|
%H | Hour (00-23) | 14 |
%I | Hour (01-12) | 02 |
%M | Minute | 30 |
%S | Second | 45 |
%f | Microsecond | 123456 |
%p | AM/PM | PM |
%Z | Time zone name | UTC |
%z | UTC offset | +0000 |
🌍 Locale-Aware Formatting
Format dates according to different locales and languages.
Setting Locale
import locale
from datetime import datetime
now = datetime.now()
# Try different locales (availability depends on system)
locales_to_try = ['en_US', 'C']
for loc in locales_to_try:
try:
locale.setlocale(locale.LC_TIME, loc)
print(f"Locale {loc}:")
print(f" Full date: {now.strftime('%A, %B %d, %Y')}")
print(f" Short date: {now.strftime('%a, %b %d')}")
break
except locale.Error:
continue
Custom Formatting Functions
from datetime import datetime
def format_date_friendly(dt):
"""Format date in a friendly, readable way"""
return dt.strftime('%B %d, %Y')
def format_time_friendly(dt):
"""Format time in a friendly way"""
return dt.strftime('%I:%M %p').lstrip('0')
def format_datetime_log(dt):
"""Format for logging purposes"""
return dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] # milliseconds
def format_filename_safe(dt):
"""Format safe for filenames"""
return dt.strftime('%Y%m%d_%H%M%S')
# Example usage
now = datetime.now()
print(f"Friendly date: {format_date_friendly(now)}")
print(f"Friendly time: {format_time_friendly(now)}")
print(f"Log format: {format_datetime_log(now)}")
print(f"Filename: {format_filename_safe(now)}")
📝 Practical Formatting Examples
Real-world examples of date formatting in different contexts.
User Interface Formatting
from datetime import datetime, timedelta
def format_relative_time(dt):
"""Format time relative to now"""
now = datetime.now()
diff = now - dt
if diff.days > 0:
return f"{diff.days} days ago"
elif diff.seconds > 3600:
hours = diff.seconds // 3600
return f"{hours} hours ago"
elif diff.seconds > 60:
minutes = diff.seconds // 60
return f"{minutes} minutes ago"
else:
return "just now"
# Example usage
recent = datetime.now() - timedelta(minutes=30)
yesterday = datetime.now() - timedelta(days=1)
print(f"Recent: {format_relative_time(recent)}")
print(f"Yesterday: {format_relative_time(yesterday)}")
Report Formatting
from datetime import datetime
def create_report_header(title):
"""Create formatted report header"""
now = datetime.now()
formatted_date = now.strftime('%B %d, %Y')
formatted_time = now.strftime('%I:%M %p')
header = f"""
{'='*50}
{title.upper()}
Generated on: {formatted_date} at {formatted_time}
{'='*50}
"""
return header
def format_event_log(events):
"""Format list of events with timestamps"""
formatted_events = []
for event in events:
timestamp = event['time'].strftime('%H:%M:%S')
formatted_events.append(f"[{timestamp}] {event['message']}")
return '\n'.join(formatted_events)
# Example usage
print(create_report_header("Daily Sales Report"))
events = [
{'time': datetime(2024, 3, 15, 9, 30), 'message': 'System startup'},
{'time': datetime(2024, 3, 15, 10, 15), 'message': 'User login'},
{'time': datetime(2024, 3, 15, 11, 0), 'message': 'Data backup completed'}
]
print(format_event_log(events))
Dynamic Date Formatting
from datetime import datetime
class DateFormatter:
"""Flexible date formatter with different styles"""
def __init__(self, dt=None):
self.dt = dt or datetime.now()
def iso(self):
return self.dt.strftime('%Y-%m-%d')
def us(self):
return self.dt.strftime('%m/%d/%Y')
def european(self):
return self.dt.strftime('%d/%m/%Y')
def readable(self):
return self.dt.strftime('%B %d, %Y')
def compact(self):
return self.dt.strftime('%Y%m%d')
def full(self):
return self.dt.strftime('%A, %B %d, %Y at %I:%M %p')
# Example usage
formatter = DateFormatter()
print(f"ISO: {formatter.iso()}")
print(f"US: {formatter.us()}")
print(f"European: {formatter.european()}")
print(f"Readable: {formatter.readable()}")
print(f"Compact: {formatter.compact()}")
print(f"Full: {formatter.full()}")
🎯 Key Takeaways
🚀 What's Next?
Now that you can format dates beautifully, learn how to calculate differences between dates and times.
Continue to: Calculate Date Differences
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.