Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import datetime
- def format_date(date: datetime, style: str = "full") -> str:
- """
- Format a datetime object into a readable string.
- Styles:
- "full" → Monday, April 07, 2026
- "short" → 07/04/2026
- "iso" → 2026-04-07
- "friendly"→ April 7, 2026
- """
- formats = {
- "full": "%A, %B %d, %Y",
- "short": "%d/%m/%Y",
- "iso": "%Y-%m-%d",
- "friendly": "%B %-d, %Y",
- }
- if style not in formats:
- raise ValueError(f"Unknown style '{style}'. Choose from: {list(formats.keys())}")
- return date.strftime(formats[style])
- # --- Example usage ---
- if __name__ == "__main__":
- now = datetime.now()
- print(format_date(now, "full")) # Monday, April 07, 2026
- print(format_date(now, "short")) # 07/04/2026
- print(format_date(now, "iso")) # 2026-04-07
- print(format_date(now, "friendly")) # April 7, 2026
Advertisement
Add Comment
Please, Sign In to add comment