Categories
Python Answers

How to convert a string into datetime with Python?

Spread the love

Sometimes, we want to convert a string into datetime with Python.

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

How to convert a string into datetime with Python?

To convert a string into datetime with Python, we can use the datetime.strptime method.

For instance, we write:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2025  1:33PM', '%b %d %Y %I:%M%p')
print(datetime_object)

We pass in a date string and a string with the date format of the date in the first argument in it.

%b is the format code for the abbreviated month.

%d is the format code for the day of the month.

%y is the format code for the 4 digit year.

It returns a date object with with the date given in the string in the first argument.

Conclusion

To convert a string into datetime with Python, we can use the 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 *