How to format dates in Python?

In Python, you can format dates using the datetime module. Here's a quick guide on how to do it:

  1. Import the module:

    from datetime import datetime
  2. Get the current date and time:

    now = datetime.now()
  3. Format the date:
    You can use the strftime method to format the date. Here are some common format codes:

    • %Y: Year (e.g., 2024)
    • %m: Month (01 to 12)
    • %d: Day of the month (01 to 31)
    • %H: Hour (00 to 23)
    • %M: Minute (00 to 59)
    • %S: Second (00 to 59)

    Example of formatting:

    formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
    print(formatted_date)  # Output: 2024-07-22 10:30:45

This will give you a string representation of the date and time in the specified format. If you need more examples or specific formats, feel free to ask!

0 Comments

no data
Be the first to share your comment!