Parse date string and change format


Question

I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this?

1
94
1/27/2018 5:35:08 PM

Accepted Answer

datetime module could help you with that:

datetime.datetime.strptime(date_string, format1).strftime(format2)

For the specific example you could do

>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
>>>
123
4/3/2019 5:54:43 PM

You can install the dateutil library. Its parse function can figure out what format a string is in without having to specify the format like you do with datetime.strptime.

from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime('%d/%m/%Y'))
# 15/02/2010

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon