Python Program to Convert String to Datetime – 2024

Hey guys, in this blog we will see a Python Program to Convert String to Datetime.

For a detailed python, DateTime tutorial check out this blog – Python Program to get the current date and time

Example 1: Using the DateTime module

from datetime import datetime

my_date_string = "Oct 04 2022 01:33PM"

datetime_object = datetime.strptime(my_date_string, '%b %d %Y %I:%M%p')

print(type(datetime_object))
print(datetime_object)

Output

<class 'datetime.datetime'>
2022-10-04 13:33:00
  • We have used the datetime.strptime() method here to parse our string to datetime dtype.
  • We have to mainly provide 2 arguments, the date string and the format in which our string date is.

Example 2: Using the dateutil module

from dateutil import parser

date_time = parser.parse("Oct 04 2022 01:33PM")

print(date_time)
print(type(date_time))

Output

2022-10-04 13:33:00
<class 'datetime.datetime'>
  • Here we have used the dateutil python module to convert our string date to a datetime object.
  • In this case we don’t have to provide the format as we did in the first example.

Check out our other python programming examples

Leave a Reply

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