from datetime import datetime # The string to be converted date_string = "2022-12-15 12:30:00" # The format in which the string represents a date and time date_format = "%Y-%m-%d %H:%M:%S" # Convert the string to a datetime object date_time = datetime.strptime(date_string, date_format) # Print the result print(date_time)
To convert a string into a datetime object in Python, you can use the strptime() method from the datetime module. This method takes the string to be converted and the format in which the string represents a date and time, and it returns a datetime object that represents the same date and time. In our example, we have a string that represents a date and time in the format "YYYY-MM-DD HH:MM:SS". After running our code, we would have a datetime object that represents the date and time specified in the date_string variable. You can then use this object in your code as needed.It's worth noting that the exact format of the date and time string can vary depending on the conventions used in your region. The strptime() method uses the same format codes as the strftime() method, which you can use to convert datetime objects to strings. You can find a complete list of these format codes in the Python documentation.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.