Home >Backend Development >Python Tutorial >How to Convert 'Mon Feb 15 2010' to '15/02/2010' in Python?
Converting Date Formats with Python
Question:
You have a date string in the format 'Mon Feb 15 2010' and want to convert it to '15/02/2010'. How can you accomplish this formatting change in Python?
Answer:
To parse the initial date string and change its format, the datetime module offers a straightforward solution:
datetime.datetime.strptime(input_date_string, input_format).strftime(output_format)
This line of code enables you to convert the input string into a datetime object using the strptime function, applying the specified input_format, and then use the strftime function to output the desired date format.
For the given example, the following code will perform the conversion:
from datetime import datetime result = datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y') print(result)
This code will output '15/02/2010', which is the specified output format.
Additional Notes:
The datetime module provides a wide range of format specifiers for both input and output. You can refer to the documentation for a complete list of these specifiers: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.
The above is the detailed content of How to Convert 'Mon Feb 15 2010' to '15/02/2010' in Python?. For more information, please follow other related articles on the PHP Chinese website!