A flexible approach is to use dateutil
's parser as in the linked question, together with a mapping dict
that maps abbreviated time zones to valid (and processable) full time zone names.
from dateutil import parser
strings = ['25 Feb 2020 02:42:20 -0800 (PST)', '25 Feb 2020 11:42:20 +0100']
tzmapping = {'PST': 'US/Pacific'} # add a key-value pair for all your timezones...
for s in strings:
print(repr(parser.parse(s, tzinfos=tzmapping)))
# datetime.datetime(2020, 2, 25, 2, 42, 20, tzinfo=tzstr('US/Pacific'))
# datetime.datetime(2020, 2, 25, 11, 42, 20, tzinfo=tzoffset(None, 3600))
If you know for sure that all of you date/time strings start with the same format and you only need the UTC offset to be parsed, a most likely faster option would be to truncate the string and parse with strptime
(as suggested by @Lambo):
from datetime import datetime
for s in strings:
print(repr(datetime.strptime(s[:26], "%d %b %Y %H:%M:%S %z")))
# datetime.datetime(2020, 2, 25, 2, 42, 20, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=57600)))
# datetime.datetime(2020, 2, 25, 11, 42, 20, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))
As for the output, I assume you need a ISO8601 compatible format. You can get that as
for s in strings:
print((datetime.strptime(s[:26], "%d %b %Y %H:%M:%S %z")).isoformat(' '))
# 2020-02-25 02:42:20-08:00
# 2020-02-25 11:42:20+01:00