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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 02:13:09174browse

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

Converting Datetime Strings to Datetime Objects

Given a list of datetime strings such as ["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"], we aim to transform them into datetime objects for further processing.

The Python package datetime provides the strptime function, designed to parse a string representation of a datetime into a timezone-naive datetime object. Its syntax is:

strptime(date_string, format)

where:

  • date_string is the input string representation of the datetime.
  • format specifies the format of the input string, using special directives to indicate the order and interpretation of the individual components.

For instance, to convert the string "Jun 1 2005 1:33PM" into a datetime object, we use the following format:

'%b %d %Y %I:%M%p'

where:

  • %b represents the abbreviated month name (e.g., Jun).
  • %d represents the day of the month (e.g., 1).
  • %Y represents the year (e.g., 2005).
  • %I represents the hour in 12-hour format (e.g., 1).
  • %M represents the minute (e.g., 33).
  • %p represents the AM/PM designator (e.g., PM).

Putting it all together, we get:

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

which returns a datetime object representing the specified datetime.

Additionally, to convert a datetime object into a date object, use the .date() method:

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

This is useful when only the date portion is required.

Refer to the linked documentation for more information on strptime and strftime formatting.

The above is the detailed content of How Can I Convert Datetime Strings to Datetime Objects in Python?. 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