Parsing ISO-8601 Date Strings
In Python, you can use the built-in datetime
module to parse ISO-8601 date strings and create datetime
objects. The datetime.fromisoformat()
function is a convenient way to do this.
Here's an example:
from datetime import datetime
iso_date_string = "2023-04-15T12:34:56Z"
datetime_obj = datetime.fromisoformat(iso_date_string)
print(datetime_obj) ## Output: 2023-04-15 12:34:56
In this example, we first import the datetime
module from the Python standard library. We then define an ISO-8601 date string and use the datetime.fromisoformat()
function to parse it and create a datetime
object.
The datetime.fromisoformat()
function can handle a variety of ISO-8601 date and time formats, including:
YYYY-MM-DD
YYYY-MM-DDThh:mm:ss
YYYY-MM-DDThh:mm:ssZ
(for UTC)
YYYY-MM-DDThh:mm:ssÂąhh:mm
(for local time zones)
If the input string does not match a valid ISO-8601 format, the datetime.fromisoformat()
function will raise a ValueError
.
Here's another example that demonstrates parsing an ISO-8601 date string with a time zone offset:
from datetime import datetime
iso_date_string = "2023-04-15T12:34:56+02:00"
datetime_obj = datetime.fromisoformat(iso_date_string)
print(datetime_obj) ## Output: 2023-04-15 12:34:56+02:00
In this case, the datetime
object includes the time zone offset information, which can be useful for working with date and time data across different time zones.