Sometimes, we want to parse a date string and change its format with Python.
In this article, we’ll look at how to parse a date string and change its format with Python.
How to parse a date string and change its format with Python?
To parse a date string and change its format with Python, we can use the datetime.datetime.striptime
method to parse a date string into a date object.
And then we call strftime
to convert the date object back to a string.
For instance, we write:
import datetime
d = datetime.datetime.strptime('Mon Feb 15 2020',
'%a %b %d %Y').strftime('%d/%m/%Y')
print(d)
We call datetime.datetime.strptime
with the date string and the format string of the date respectively.
%a
is the abbreviation of the day of the week.
%b
is the abbreviation of the month.
%d
is the day of the month.
And %Y
is the year.
We then call strftime
to return a date string with the format we want.
%m
is the 2 digit month.
Therefore, d
is '15/02/2020'
.
Conclusion
To parse a date string and change its format with Python, we can use the datetime.datetime.striptime
method to parse a date string into a date object.
And then we call strftime
to convert the date object back to a string.