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')
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)
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')
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!