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:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3