strptime is a method available in Python’s datetime module. It stands for “string parse time”. It is used to convert a string representing a date or time into a datetime object. The method takes two arguments:
- The string representing the date or time
- The format string specifying the expected format of the date or time
The format string is a combination of various format codes that represent different parts of the date and time, such as %Y for a 4-digit year, %m for a 2-digit month, %d for a 2-digit day, %H for a 2-digit hour, %M for a 2-digit minute, and %S for a 2-digit second.
Here’s an example:
from datetime import datetime
date_string = “2023-04-26 12:34:56”
date_format = “%Y-%m-%d %H:%M:%S”
# Convert the date_string into a datetime object
date_obj = datetime.strptime(date_string, date_format)
print(date_obj)
This code will output:
2023-04-26 12:34:56
In this example, the string “2023-04-26 12:34:56” is converted into a datetime object using the format string “%Y-%m-%d %H:%M:%S”, which matches the format of the input string.