Categories
Python Answers

How to convert a date string to date object with Python?

Spread the love

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

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

How to convert a date string to date object with Python?

To convert a date string to date object with Python, we can use the datetime.datetime.strptime method.

For instance, we write:

import datetime

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

to convert the '24052010' string into a date object.

We parse the string by passing in "%d%m%Y" as the format string.

%d is the 2 digit date of the month.

%m is the 2 digit month.

And %Y is the 4 digit year.

Then we call date to return the date from the date time object.

Therefore, d is 2010-05-24.

Conclusion

To convert a date string to date object with Python, we can use the datetime.datetime.strptime method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *