"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 "Jun 1 2005 1:33PM" Strings to Python DateTime Objects?

How to Convert "Jun 1 2005 1:33PM" Strings to Python DateTime Objects?

Posted on 2025-03-24
Browse:405

How to Convert

Convert String "Jun 1 2005 1:33PM" into Datetime

Given a list of datetime strings like "Jun 1 2005 1:33PM", how can you convert them into datetime objects?

Solution:

datetime.strptime provides the solution for parsing datetime strings into datetime objects. By specifying the expected format as the second argument, datetime.strptime can interpret the string and convert it into the appropriate datetime object:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')

In this instance, the provided format string follows the syntax:

  • '%b': Abbreviated month name
  • '%d': Day of the month
  • '%Y': Year
  • '%I': Hour (12-hour clock)
  • '%M': Minute
  • '%p': AM/PM indicator

By following this format string, datetime.strptime accurately parses the input string into a datetime object.

To obtain a date object from the datetime object, use the .date() method:

date_object = datetime_object.date()

Additional Resources:

  • [strptime Documentation](https://docs.python.org/3/library/datetime.html#datetime.strptime)
  • [strptime/strftime Format String Documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)
  • [strftime.org Format String Cheatsheet](https://strftime.org/)
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