Home >Backend Development >Python Tutorial >How Can I Convert Datetime Strings to Datetime Objects in Python?
Given a list of datetime strings such as ["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"], we aim to transform them into datetime objects for further processing.
The Python package datetime provides the strptime function, designed to parse a string representation of a datetime into a timezone-naive datetime object. Its syntax is:
strptime(date_string, format)
where:
For instance, to convert the string "Jun 1 2005 1:33PM" into a datetime object, we use the following format:
'%b %d %Y %I:%M%p'
where:
Putting it all together, we get:
datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
which returns a datetime object representing the specified datetime.
Additionally, to convert a datetime object into a date object, use the .date() method:
datetime.strptime('Jun 1 2005', '%b %d %Y').date()
This is useful when only the date portion is required.
Refer to the linked documentation for more information on strptime and strftime formatting.
The above is the detailed content of How Can I Convert Datetime Strings to Datetime Objects in Python?. For more information, please follow other related articles on the PHP Chinese website!