Python String To Datetime
Chapter:
Python
Last Updated:
23-07-2023 15:09:43 UTC
Program:
/* ............... START ............... */
from datetime import datetime
# Sample string
date_string = "2023-07-23 12:34:56"
# Define the format of the string using format codes
format_string = "%Y-%m-%d %H:%M:%S"
# Use strptime() to convert the string to a datetime object
datetime_object = datetime.strptime(date_string, format_string)
# Now you have the datetime object
print(datetime_object)
/* ............... END ............... */
Output
Notes:
-
To convert a string to a datetime object in Python, you can use the datetime module. The strptime() function is used to parse the string and create a datetime object based on a specified format.
- Here's a step-by-step guide on how to do it:
- Step 1: Import the datetime module.
- Step 2: Use the strptime() function to parse the string and create a datetime object.
- Step 3: Specify the format of the string using format codes.
- In this example, the format code %Y represents the year with century as a decimal number, %m represents the month as a zero-padded decimal number, %d represents the day of the month as a zero-padded decimal number, %H represents the hour (24-hour clock) as a zero-padded decimal number, %M represents the minute as a zero-padded decimal number, and %S represents the second as a zero-padded decimal number.