How to Convert Timestamps with Timezone Offsets to Python datetime Objects?

DDD
Release: 2024-11-27 05:48:09
Original
419 people have browsed it

How to Convert Timestamps with Timezone Offsets to Python datetime Objects?

Converting Timestamps with Offset to Datetime Objects Using strptime

Converting timestamps from the format "YYYY-MM-DDTHH:MM:SS-hh:mm" to datetime objects in Python using the strptime method can be challenging due to the time offset information.

In the example provided, strptime fails to parse the timestamp with the offset "-07:00" using the "%Y-%m-%dT%H:%M:%S-%z" format. This is because strptime does not natively support the '%z' directive for timezones in Python 2.

Workaround Options:

1. Ignore the Timezone:

If the timezone information is not crucial, you can ignore it by parsing the string up to the offset:

time_str = "2012-07-24T23:14:29-07:00"
time_obj = datetime.datetime.strptime(time_str[:19], '%Y-%m-%dT%H:%M:%S')
Copy after login

2. Use the dateutil Module:

Alternatively, the dateutil module provides a more robust parsing function that supports timezones:

from dateutil.parser import parse
time_obj = parse(time_str)
Copy after login

Python 3 Support:

In Python 3.2 and later, there is improved support for timezone handling. Removing the last ":" from the offset and replacing "-" with " ":

time_str = "2012-07-24T23:14:29-07:00"
time_obj = datetime.datetime.strptime(''.join(time_str.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
Copy after login

This will correctly parse the timestamp and create a datetime object with the specified timezone offset.

The above is the detailed content of How to Convert Timestamps with Timezone Offsets 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template