Set String to datetime Object in Python (3 Examples)

This article explains how to transform a string to a datetime object in Python.

Load datetime Module & Generate Example Data

We have to import the datetime module as shown below:

from datetime import datetime

Now we can create a string containing a time and a date that we can use in the following examples.

string_x = '08/12/23 12:35:40'
# 08/12/23 12:35:40

Example 1: Set String to datetime Object

The strptime() function of the datetime module takes the date string (month, day, and year) as input and returns it as a datetime object.

datetime_x = datetime.strptime(string_x, '%m/%d/%y %H:%M:%S')
# 2023-08-12 12:35:40

A new datetime object has been created containing the date and time of our input string.

Example 2: Return Only Time from String

We can apply the time() function to get only the time of a string with date and time components:

my_time = datetime.strptime(string_x, '%m/%d/%y %H:%M:%S').time()
# 12:35:40

Example 3: Return Only Date from String

By using the strptime() function in addition with the date() function, we can return only the date from a character string:

my_date = datetime.strptime(string_x, '%m/%d/%y %H:%M:%S').date()
# 2023-08-12


Further Resources

Please find some related tutorials below.


Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed