Skip to main content

How to convert a string to a datetime object in Python

How to convert a string to a datetime object in Python.

Here's a step-by-step tutorial on how to convert a string to a datetime object in Python:

  1. First, you need to import the datetime module. This module provides classes for manipulating dates and times in Python. You can do this by adding the following line at the beginning of your code:
   import datetime
  1. Next, you need to create a string that represents the date and time you want to convert. Make sure the string is in a format that can be recognized as a date and time. For example, let's say you have the following string:
   date_string = "2022-01-01 10:30:00"
  1. Now, you can use the datetime.strptime() function to convert the string to a datetime object. This function takes two arguments: the string you want to convert and a format string that specifies the format of the input string. In our example, the format string would be "%Y-%m-%d %H:%M:%S". Here's how you can do it:
   datetime_object = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

The strptime() function parses the input string using the format string and returns a datetime object.

  1. Finally, you can now use the datetime object to perform various operations or extract specific information from it. For example, you can print the converted datetime object:
   print(datetime_object)

This will output:

   2022-01-01 10:30:00

And that's it! You have successfully converted a string to a datetime object in Python. Here's the complete code:

import datetime

date_string = "2022-01-01 10:30:00"
datetime_object = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(datetime_object)

Feel free to modify the date_string and format string to match your specific date and time format.