Convert String Datetime Strings to Datetime Objects
Many applications work with timestamps in the form of strings. It becomes necessary to convert these strings into datetime objects for further processing. Here's how to convert strings like "Jun 1 2005 1:33PM" into datetime objects:
The datetime.strptime function in Python effortlessly parses input strings according to a user-defined format, returning timezone-naive datetime objects:
>>> from datetime import datetime >>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') datetime.datetime(2005, 6, 1, 13, 33)
To obtain a date object from a datetime object, use the .date() method:
>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date() date(2005, 6, 1)
Additional resources:
Remember that strptime stands for "string parse time" and strftime for "string format time."
The above is the detailed content of How Can I Convert String Datetime Strings to Python Datetime Objects?. For more information, please follow other related articles on the PHP Chinese website!