Home > Backend Development > Python Tutorial > How to Convert String Dates to Python Datetime Objects?

How to Convert String Dates to Python Datetime Objects?

Patricia Arquette
Release: 2024-12-25 10:00:18
Original
992 people have browsed it

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

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

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.

The above is the detailed content of How to Convert String Dates 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