Python String to DateTime Object

To convert string to DateTime object in Python, you can use datetime.datetime.strptime() function.

The syntax of strptime() is given below.

</>
Copy
strptime(date_string, format)

The function returns new datetime object parsed from date_string using the specified format.

Example 1 – Convert Python String to DateTime Object

In the following program, we shall take a string and format using which we have to convert the date string to datetime object.

For the format codes we used in format string, please refer Python DateTime Format.

Python Program

</>
Copy
from datetime import datetime

date_string = '05/28/2020 23:05:24'
format = '%m/%d/%Y %H:%M:%S'
dt = datetime.strptime(date_string, format)

print(dt)

Output

2020-05-28 23:05:24

Example 2 – Convert Python String to DateTime Object – Only Date Specified

In the following program, we shall take a string that has only month, day and year. And format this string to datetime object using strptime() function.

Python Program

</>
Copy
from datetime import datetime

date_string = '05/28/2020'
format = '%m/%d/%Y'
dt = datetime.strptime(date_string, format)

print(dt)

Output

2020-05-28 00:00:00

The date that we provided in the string is set as is in the datetime object. But, for the time, the default values have been taken. The default value for hours is 00, minutes is 00, and seconds is 00.

Example 3 – Convert Python String to DateTime Object – Only Time Specified

In the following program, we shall take a string that has only hours, minutes and seconds. And format this string to datetime object using strptime() function.

Python Program

</>
Copy
from datetime import datetime

date_string = '23:05:24'
format = '%H:%M:%S'
dt = datetime.strptime(date_string, format)

print(dt)

Output

1900-01-01 23:05:24

The time that we provided in the string is set as is in the datetime object. For the date, the default values have been taken. The default value for year is 1900, month is 01, and day is 01.

Conclusion

Concluding this Python Tutorial, we can provide date and time information as string and convert it into datetime object using the specified format and strptime() function.