Home >Backend Development >Python Tutorial >How to Efficiently Parse ISO 8601 Strings into Python datetime Objects?

How to Efficiently Parse ISO 8601 Strings into Python datetime Objects?

Susan Sarandon
Susan SarandonOriginal
2024-12-18 03:46:15265browse

How to Efficiently Parse ISO 8601 Strings into Python datetime Objects?

How to Parse ISO 8601 Strings into Python Datetime Objects

ISO 8601 is a widely used standard for representing dates and times. It is often used in data exchange and web services. However, parsing ISO 8601 strings into Python datetime objects can be a bit challenging.

A Hackish Approach

One common approach is to use the time.strptime() function to parse the string. However, this approach can be tedious and error-prone. Here's an example:

datetime.datetime(*time.strptime("2009-05-28T16:15:00", "%Y-%m-%dT%H:%M:%S")[:6])

A Cleaner Solution

Fortunately, there are more elegant ways to parse ISO 8601 strings. The dateutil library provides a convenient function called parser.parse():

from dateutil import parser

yourdate = parser.parse("2009-05-28T16:15:00")

This function can handle a wide range of ISO 8601 formats, including strings with timezones.

Example Usage

Here are some examples of how to use the parser.parse() function:

# Parse a basic ISO 8601 string
dateutil.parser.parse("2009-05-28T16:15:00Z")

# Parse a string with a timezone offset
dateutil.parser.parse("2009-05-28T16:15:00-05:00")

# Parse a string with a fractional second
dateutil.parser.parse("2009-05-28T16:15:00.123Z")

The parser.parse() function returns a datetime object that you can use in your Python code.

The above is the detailed content of How to Efficiently Parse ISO 8601 Strings into 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