Converting String Dates to Python Datetime Objects
Many datasets include timestamps as strings, such as "Jun 1 2005 1:33PM." Converting these strings to Python datetime objects simplifies data manipulation and analysis.
To achieve this, utilize the strptime method from the datetime module. This function parses the input string into its respective datetime components. For the string format shown in the example, use the '%b %d %Y %I:%M%p' format string:
import datetime date_string = "Jun 1 2005 1:33PM" date_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p') print(date_object) # Output: datetime.datetime(2005, 6, 1, 13, 33)
To obtain the date portion of the datetime object as a separate date object, use the .date() method:
date_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p').date() print(date_object) # Output: date(2005, 6, 1)
Additional notes:
The above is the detailed content of How to Convert String Dates to Python Datetime Objects?. For more information, please follow other related articles on the PHP Chinese website!