Home >Backend Development >Python Tutorial >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?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 19:38:14688browse

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/)

The above is the detailed content of How to Convert 'Jun 1 2005 1:33PM' Strings to Python DateTime Objects?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn