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 |
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' print(string_x) # 08/12/23 12:35:40 |
string_x = '08/12/23 12:35:40' print(string_x) # 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') print(datetime_x) # 2023-08-12 12:35:40 |
datetime_x = datetime.strptime(string_x, '%m/%d/%y %H:%M:%S') print(datetime_x) # 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() print(my_time) # 12:35:40 |
my_time = datetime.strptime(string_x, '%m/%d/%y %H:%M:%S').time() print(my_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() print(my_date) # 2023-08-12 |
my_date = datetime.strptime(string_x, '%m/%d/%y %H:%M:%S').date() print(my_date) # 2023-08-12
Further Resources
Please find some related tutorials below.
- Set datetime Object to Date Only String in Python (3 Examples)
- Transform datetime into String with Milliseconds in Python (3 Examples)
- Transform datetime to String without Microsecond Component in Python (3 Examples)
- All Python Programming Tutorials
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.