Learn how to format dates and times in Python using the strftime function with examples.
Python's strftime function is a powerful tool for formatting date and time objects. It is part of the datetime module, which allows developers to create string representations of dates and times in a variety of formats, essential for displaying timestamps in a user-friendly manner.
The strftime function stands for 'string format time'. By using format codes, you can convert datetime objects to strings that represent dates and times in human-readable formats. For example, '%Y-%m-%d' formats a date like '2023-10-14'. By using various format codes, you can customize the output to meet specific needs.
When using strftime, it's important to follow best practices to ensure correct outputs. Always use the appropriate format codes for your desired output. Consider the locale settings if your application needs to support international date and time formats. Testing different outputs with sample data can prevent errors in production.
A common mistake when using strftime is mismatching format codes, which can lead to incorrect date and time outputs. Ensure that the format codes match the type of data you are working with. Another issue is forgetting to import the datetime module, which is necessary for using strftime.
from datetime import datetime
now = datetime.now()
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_date)from datetime import datetime
date_string = '2023-10-14 12:30:00'
date_object = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
print(date_object.strftime('%A, %B %d, %Y'))