Home >Backend Development >Python Tutorial >How to Convert Timestamps with Timezone Offsets to DateTime Objects in Python?
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')
However, using the provided time offset results in a ValueError due to the 'z' directive not being supported.
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')
2. Use dateutil.parser:
The dateutil module offers a parse function that supports timezones:
from dateutil.parser import parse time_obj = parse(time_str)
For Python versions 3.2 and above, timezone support has been enhanced. %z will function after adjusting the format string as follows:
time_obj = datetime.datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S%z')
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!