Python datetime.strptime()
In Python, the strptime()
method of the datetime
module is used to convert a string representation of a date and time into a datetime
object.
The syntax for using strptime()
is as follows:
datetime.datetime.strptime(date_string, format)
where date_string
is the string to be parsed and format
is the format string that specifies the format of the input string.
The format
string contains various format codes that represent different components of the date and time, such as %Y
for the year, %m
for the month, %d
for the day, %H
for the hour, %M
for the minute, %S
for the second, and %f
for microseconds.
Here is an example of how to use strptime()
to convert a string to a datetime
object:
import datetime date_string = "2023-02-27 13:45:30" format = "%Y-%m-%d %H:%M:%S" datetime_obj = datetime.datetime.strptime(date_string, format) print(datetime_obj)
Output:
2023-02-27 13:45:30
In this example, we first import the datetime
module. We then define a string date_string
that represents the date and time we want to parse. We also define a format
string that specifies the format of the input string. We then use the strptime()
method to parse the input string and create a datetime
object datetime_obj
. Finally, we print the datetime_obj
.