Parsing Dates and Times from Strings
The datetime
module also provides the strptime()
class method, which can be used to parse a string and create a datetime
object. This method takes two arguments: the string to be parsed, and a format string that specifies the expected format of the input string. For example, the following code parses a string in the format "YYYY-MM-DD HH:MM:SS" and creates a datetime
object:
s = '2021-12-31 12:30:15'
dt = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
print(dt)
It will print "2021-12-31 12:30:15"
The format string is a string of characters that correspond to the different parts of a date and time, such as the year, month, day, hour, minute, and second.
Here are some of the most commonly used characters in the format string:
%Y
: year with century as a decimal number. For example, "2022"
%m
: month as a zero-padded decimal number. For example, "01" for January, "12" for December
%d
: day of the month as a zero-padded decimal number. For example, "01" for the first day of the month, "31" for the last day of the month
%H
: hour (24-hour clock) as a zero-padded decimal number. For example, "00" for midnight, "12" for noon, "23" for 11 PM
%M
: minute as a zero-padded decimal number. For example, "00" for the top of the hour, "30" for half past the hour
%S
: second as a zero-padded decimal number. For example, "00" for the start of the minute, "59" for the end of the minute
In addition to these characters, the format string can also include literal characters that will be matched against the input string. For example, the following format string will match a date in the format "YYYY-MM-DD":
fmt = '%Y-%m-%d'
The strptime()
method will then use this format string to parse the input string, and extract the year, month, and day from it.
It is important to note that the format string must match the input string exactly, otherwise an exception will be raised. If you are unsure about the format of the input string, you can use the try
and except
statements to handle any potential exceptions that may be raised.
Also, the strptime()
method is not widely recommended due to some issues like it is not thread-safe and it is slow. It is recommended to use the dateutil.parser.parse()
function, which is more flexible and more efficient.