Menu Close

How to convert Python date string to date object?

Sometimes, we want to convert Python date string to date object.

In this article, we’ll look at how to convert Python date string to date object.

How to convert Python date string to date object?

To convert Python date string to date object, we use the strptime method.

For instance, we write

import datetime

d = datetime.datetime.strptime('24052022', "%d%m%Y").date()

to call strptime with a date string and a string with the format of the date string to parse the date string into a datetime object.

Then we call date to get the date object.

%d is the 2 digit date.

%m is the 2 digit month.

And %Y is the 4 digit year.

Conclusion

To convert Python date string to date object, we use the strptime method.

Posted in Python, Python Answers