Home >Backend Development >Python Tutorial >Why Doesn't Python's `strptime()` Preserve Time Zones, and What's the Best Alternative?
Problem:
When attempting to parse date and time strings with time zones using Python's strptime() function, you've noticed that the returned datetime object lacks time zone information. Despite consulting the documentation, you can't find any documented reference to this behavior.
Answer:
While the documentation for strptime() does not explicitly state its omission of time zones, it is known to silently discard them. However, there is an alternative solution for accurately preserving time zones.
Solution:
To effectively manage time zones while parsing date and time strings, it is recommended to utilize the python-dateutil module. Its parser offers comprehensive date format handling, including time zones.
Demonstration:
from dateutil import parser # Parsing a date with an explicit time zone parsed_datetime = parser.parse("Tue Jun 22 07:46:22 EST 2010") print(parsed_datetime.tzinfo) # Outputs 'tzlocal()' (local time zone)
Conclusion:
By using the python-dateutil parser, you can efficiently parse date and time strings with preserved time zones, eliminating the need to contend with strptime()'s limitations.
The above is the detailed content of Why Doesn't Python's `strptime()` Preserve Time Zones, and What's the Best Alternative?. For more information, please follow other related articles on the PHP Chinese website!