Home >Backend Development >Python Tutorial >How Can I Convert String Datetime Strings to Python Datetime Objects?

How Can I Convert String Datetime Strings to Python Datetime Objects?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 09:19:13633browse

How Can I Convert String Datetime Strings to Python Datetime Objects?

Convert String Datetime Strings to Datetime Objects

Many applications work with timestamps in the form of strings. It becomes necessary to convert these strings into datetime objects for further processing. Here's how to convert strings like "Jun 1 2005 1:33PM" into datetime objects:

The datetime.strptime function in Python effortlessly parses input strings according to a user-defined format, returning timezone-naive datetime objects:

>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)

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

>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)

Additional resources:

  • [strptime documentation](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime)
  • [strptime/strftime format string documentation](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-format-codes)
  • [strftime.org format string cheatsheet](https://www.strftime.org/)

Remember that strptime stands for "string parse time" and strftime for "string format time."

The above is the detailed content of How Can I Convert String Datetime 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