Python String to DateTime

Converting python string to datetime and vice versa.

August 3, 2024
Reading Time: 1 minutes

Python is well suited for use in scripting and web development and converting a string to a datetime and vice versa is a popular tool in its belt.

In this tutorial, we will see how to easily convert a string with certain format to a datetime data type in python as well as converting a datetime to a string in any format we want.

Converting String to Date Time

Let's say you have a string in the format mm/dd/yyyy such as 05/31/1988 and you want it to convert into a date data type so you can manipulate it using date methods, it can be done easily. Let's see how to do it in python.

from datetime import datetime

date_str = '05/31/1988'

date = datetime.strptime(date_str + ' 00:00:00', '%m/%d/%Y 00:00:00')

print(type(date))

This will print out

<class 'datetime.datetime'>

Converting Date Time to String

Converting from a datetime data type to string is more straightforward in python.

Now for example you have a datetime object and you want it to convert to string in the format January 1, 1970,

from datetime import datetime

date = datetime.today() # Store the current date and time to date variable

date_str = datetime.strftime(date, '%B %d, %Y')  # Convert to the format January 1, 1970
print(date_str)

As of this day of this writing, this will output

August 03, 2024

I hope you get value from this content. Happy coding!