Home > Backend Development > Python Tutorial > How to Convert Timestamps with Timezone Offsets to DateTime Objects in Python?

How to Convert Timestamps with Timezone Offsets to DateTime Objects in Python?

Barbara Streisand
Release: 2024-11-29 19:37:11
Original
1051 people have browsed it

How to Convert Timestamps with Timezone Offsets to DateTime Objects in Python?

Convert Timestamps with Offset to Datetime Objects Using strptime

Problem

Converting timestamps of the format "2012-07-24T23:14:29-07:00" to datetime objects using strptime() can be problematic due to the time offset at the end (-07:00). Without the offset, it's possible to use strptime() as follows:

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

However, using the provided time offset results in a ValueError due to the 'z' directive not being supported.

Workarounds

There are two primary workarounds:

1. Ignore the Timezone Using strptime():

Remove the timezone portion from the timestamp before parsing:

time_obj = datetime.datetime.strptime(time_str[:19], '%Y-%m-%dT%H:%M:%S')
Copy after login

2. Use dateutil.parser:

The dateutil module offers a parse function that supports timezones:

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

Python 3.2 and Newer

For Python versions 3.2 and above, timezone support has been enhanced. %z will function after adjusting the format string as follows:

  • Remove the last colon from the format string.
  • Remove the '-' before the %z specifier.
time_obj = datetime.datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S%z')
Copy after login

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