Home > Article > Backend Development > Can I Preserve Timezone Information When Using strptime() in Python?
Datetime.strptime() and Timezone Preservation
Problem:
When parsing date/time strings with strptime(), the timezone appears to be discarded from the resulting datetime object, despite documentation suggesting otherwise.
Question:
Is there a way to preserve timezone information when using strptime(), or are there alternative approaches to string parsing?
Answer:
While strptime() lacks built-in support for preserving timezones, utilizing the python-dateutil library provides a robust alternative:
from dateutil import parser parser.parse("Tue Jun 22 07:46:22 EST 2010")
This snippet demonstrates the powerful capabilities of parser. It effortlessly handles various date formats, including:
parser.parse("Fri, 11 Nov 2011 03:18:09 -0400") parser.parse("Sun") parser.parse("10-11-08")
Advantages of dateutil.parser:
The above is the detailed content of Can I Preserve Timezone Information When Using strptime() in Python?. For more information, please follow other related articles on the PHP Chinese website!