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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github