Parsing Timestamp Strings with Abbreviated Timezone Names in Python
Parsing timestamp strings with abbreviated timezone names poses a unique challenge in Python. The built-in dateutil library provides a parser.parse() function that facilitates timestamp parsing, but it does not inherently address timezone abbreviations.
To tackle this issue, a simple and effective solution utilizes the tzinfos keyword argument in parser.parse(). This argument accepts a dictionary mapping timezone abbreviations to their corresponding GMT offsets in seconds.
To populate the tzinfos dictionary, a list of timezone abbreviations and offsets can be manually created or obtained from external sources. Once the dictionary is established, the following code demonstrates how to parse timestamp strings and retrieve their corresponding timezones:
import dateutil.parser as dp
s = 'Sat, 11/01/09 8:00PM'
# Create timezone abbreviation to offset dictionary
tzd = {
'PST': -8*3600,
'PDT': -7*3600,
'MST': -7*3600,
'MDT': -6*3600,
'CST': -6*3600,
'CDT': -5*3600,
'EST': -5*3600,
'EDT': -4*3600
}
for tz_code in ('PST','PDT','MST','MDT','CST','CDT','EST','EDT'):
dt = s ' ' tz_code
print(dt, '=', dp.parse(dt, tzinfos=tzd))
This code iterates through the provided timezone abbreviations, and for each abbreviation, it parses the timestamp string and displays the parsed datetime object along with the corresponding timezone name.
This approach effectively handles timestamp strings with abbreviated timezones, allowing for easy parsing and interpretation.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3