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
Release: 2024-12-24 19:38:14
Original
693 people have browsed it

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')
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template