"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to convert a string date to a Python date object?

How to convert a string date to a Python date object?

Posted on 2025-04-17
Browse:594

How to Convert String Dates to Python Datetime Objects?

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:

  • strptime stands for "string parse time."
  • strftime (not covered in this response) stands for "string format time."
  • Consult the documentation provided in the reference links for more information on strptime and strftime format strings.
Latest tutorial More>

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