Sometimes, we want to parse a date string and change format with Python.
In this article, we’ll look at how to parse a date string and change format with Python.
How to parse a date string and change format with Python?
To parse a date string and change format with Python, we can call strptime
to parse a date string into a datetime object.
And then we call strftime
on the datetime object to return a date string in the new format.
For instance, we write
import datetime
d = datetime.datetime.strptime('Thu Apr 07 2022', '%a %b %d %Y').strftime('%d/%m/%Y')
to call datetime.datetime.strptime
with the 'Thu Apr 07 2022'
date string and the '%a %b %d %Y'
format string to parse it into a datetime object.
Then we call strftime
with a new format string to return a date string in the new format.
Conclusion
To parse a date string and change format with Python, we can call strptime
to parse a date string into a datetime object.
And then we call strftime
on the datetime object to return a date string in the new format.