How can I parse date in Python and change its format?
I have a date string in the format ‘Mon Feb 15 2010’, and I want to change it to the format ‘15/02/2010’. How can I achieve this in Python?
How can I parse date in Python and change its format?
I have a date string in the format ‘Mon Feb 15 2010’, and I want to change it to the format ‘15/02/2010’. How can I achieve this in Python?
Hi Archna,
You can do this using datetime.strptime and strftime
from datetime import datetime
# Original date string
date_str = 'Mon Feb 15 2010'
# Parse the date and change format
parsed_date = datetime.strptime(date_str, '%a %b %d %Y')
formatted_date = parsed_date.strftime('%d/%m/%Y')
print(formatted_date)
In this solution, strptime is used to parse the date from the original format, and strftime is used to format it to the desired ‘15/02/2010’ format.
This can also be done using dateutil.parser module
from dateutil import parser
# Original date string
date_str = 'Mon Feb 15 2010'
# Parse the date and change format
parsed_date = parser.parse(date_str)
formatted_date = parsed_date.strftime('%d/%m/%Y')
print(formatted_date)
This approach uses the dateutil.parser module to automatically parse the date string, followed by strftime to format it as needed.
Also, you can try using pandas.to_datetime
import pandas as pd
# Original date string
date_str = 'Mon Feb 15 2010'
# Parse the date and change format
parsed_date = pd.to_datetime(date_str)
formatted_date = parsed_date.strftime('%d/%m/%Y')
print(formatted_date)
This solution uses pandas.to_datetime to parse the date string and then formats it using strftime.