How to convert string into datetime in Python?

Better Stack Team
Updated on January 26, 2023

To convert a string into a datetime object in Python, you can use the datetime.strptime() function. This function allows you to specify the format of the input string, and it will return a datetime object that corresponds to the input string.

Here is an example of how you can use strptime() to convert a string into a datetime object:

 
from datetime import datetime

date_string = "2022-01-25 13:00:00"
date_format = "%Y-%m-%d %H:%M:%S"

date_object = datetime.strptime(date_string, date_format)

print(date_object)

This will output the following datetime object: 2022-01-25 13:00:00.

You can also use the dateutil module to parse strings into datetime objects. The dateutil.parser.parse() function is able to parse a wide range of string formats, and it can handle ambiguous strings (e.g. "Jan 1 2022") without the need to specify a format string. Here is an example of how you can use dateutil to parse a string into a datetime object:

 
from dateutil import parser

date_string = "2022-01-25 13:00:00"

date_object = parser.parse(date_string)

print(date_object)

This will output the following datetime object: 2022-01-25 13:00:00.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →