CanadaTechLife

Python Date Formatter - Canadian Format

Apr 7th, 2026
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. from datetime import datetime
  2.  
  3. def format_date(date: datetime, style: str = "full") -> str:
  4.     """
  5.    Format a datetime object into a readable string.
  6.  
  7.    Styles:
  8.        "full"    → Monday, April 07, 2026
  9.        "short"   → 07/04/2026
  10.        "iso"     → 2026-04-07
  11.        "friendly"→ April 7, 2026
  12.    """
  13.     formats = {
  14.         "full":     "%A, %B %d, %Y",
  15.         "short":    "%d/%m/%Y",
  16.         "iso":      "%Y-%m-%d",
  17.         "friendly": "%B %-d, %Y",
  18.     }
  19.  
  20.     if style not in formats:
  21.         raise ValueError(f"Unknown style '{style}'. Choose from: {list(formats.keys())}")
  22.  
  23.     return date.strftime(formats[style])
  24.  
  25.  
  26. # --- Example usage ---
  27. if __name__ == "__main__":
  28.     now = datetime.now()
  29.  
  30.     print(format_date(now, "full"))      # Monday, April 07, 2026
  31.     print(format_date(now, "short"))     # 07/04/2026
  32.     print(format_date(now, "iso"))       # 2026-04-07
  33.     print(format_date(now, "friendly"))  # April 7, 2026
Advertisement
Add Comment
Please, Sign In to add comment