September 11, 2024

Python strftime() Function

The strftime() function in Python is used to format date and time objects into readable strings. This function is a method of the datetime class and allows you to specify the format of the output using format codes. It’s part of the datetime module, which provides classes for manipulating dates and times.

1. Basic Syntax

from datetime import datetime

# Create a datetime object
now = datetime.now()

# Format datetime object to string
formatted_date = now.strftime(format)
    

Here, format is a string that specifies the desired format for the output.

2. Common Format Codes

Below are some commonly used format codes for the strftime() function:

  • %Y – Year with century (e.g., 2024)
  • %y – Two-digit year (e.g., 24)
  • %m – Month as a zero-padded decimal number (e.g., 09)
  • %d – Day of the month as a zero-padded decimal number (e.g., 01)
  • %H – Hour (24-hour clock) as a zero-padded decimal number (e.g., 14)
  • %I – Hour (12-hour clock) as a zero-padded decimal number (e.g., 02)
  • %M – Minute as a zero-padded decimal number (e.g., 05)
  • %S – Second as a zero-padded decimal number (e.g., 09)
  • %p – AM or PM
  • %A – Weekday name (e.g., Monday)
  • %B – Month name (e.g., September)

3. Examples

Example 1: Basic Date and Time Formatting

from datetime import datetime

# Current date and time
now = datetime.now()

# Format datetime object to string
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)  # Output: 2024-09-01 14:05:09
    

Example 2: Custom Date Formats

from datetime import datetime

# Create a datetime object
now = datetime.now()

# Custom format
formatted_date = now.strftime("Today is %A, %B %d, %Y")
print(formatted_date)  # Output: Today is Sunday, September 01, 2024
    

Example 3: 12-Hour Clock Format

from datetime import datetime

# Create a datetime object
now = datetime.now()

# 12-hour clock format with AM/PM
formatted_time = now.strftime("%I:%M %p")
print(formatted_time)  # Output: 02:05 PM
    

4. Error Handling

Ensure that the format string provided to strftime() is valid. Incorrect format codes or mismatched codes may result in errors or unexpected output. Always verify the format codes used to match the desired output.

5. Conclusion

The strftime() function is a powerful tool for formatting date and time objects into human-readable strings. By understanding and using the appropriate format codes, you can customize the representation of date and time to fit various needs and contexts.