i2tutorials

Converting string into datetime in Python

 

We can convert a string representation of date and time into a date object using the two methods mentioned below

 

Using the datetime module:

We import a datetime class named datetime from the datetime module. We use this class to call the strptime() method. The strptime() method creates a datetime object from the given string. 

 

Note: We cannot create a datetime object from every string. The string needs to be in a certain format.

 

This method takes two arguments 

 

The most frequently used format codes are 

Example: 01, 02, …, 31

Example: January, February etc.

Example: 2018, 2019 etc.

Example:01, 02, …, 12

Example:01, 02, …, 59

 

Example:

from datetime import datetime

date_time_string = "Aug 15 2021 12:45PM"

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

print(type(datetime_object))
print(datetime_object)

Output:

 

Using the dateutil module:

From the dateutil module we import the parser class using which we call the parser() class method. We only pass one parameter which is the string. 

 

Example:

from dateutil import parser

date_time = parser.parser("Aug 15 2021 12:45PM")

print(date_time)
print(type(date_time))

Output:

 

Exit mobile version