/  Technology   /  Converting string into datetime in Python
Converting string into datetime in Python

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 datetime module
  • Using dateutil module

 

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 

  • string which represents date and time
  • format code 

 

The most frequently used format codes are 

  • %d which represents the day of the month. 

Example: 01, 02, …, 31

  • %B which represents the complete month’s name .

Example: January, February etc.

  • %Y which represents the year that is four digits long. 

Example: 2018, 2019 etc.

  • %I which represents 12 hour clock as a zero padded decimal 

Example:01, 02, …, 12

  • %p which represents whether it’s AM or PM.
  • %M which represents minutes as a zero-padded decimal.

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:

 

Leave a comment