Converting string to DateTime using strptime()

Here we are going to convert a simple string into datetime object, for this we will pass the string into strptime() and objectify the datetime object through this.

Python3




from datetime import datetime
 
input_str = '21/01/24 11:04:19'
 
dt_object = datetime.strptime(
  input_str, '%d/%m/%y %H:%M:%S')
 
print("The type of the input date string now is: ",
      type(dt_object))
 
print("The date is", dt_object)


Output: 

The type of the input date string now is:  <class ‘datetime.datetime’>

The date is 2024-01-21 11:04:19

Create Python Datetime from string

In this article, we are going to see how to create a python DateTime object from a given string.

For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user.

Syntax

datetime.strptime(date_string, format)

Similar Reads

Converting string to DateTime using strptime()

Here we are going to convert a simple string into datetime object, for this we will pass the string into strptime() and objectify the datetime object through this....

Converting string containing words to datetime using strptime()

...

Python strptime() ValueError

The strptime() method allows you to convert timestamps in “words” to date-time objects too. The snippet below shows it can be done:...

Format Code List

...