简体   繁体   中英

Convert non-UTC time string with timezone abbreviation into UTC time in python, while accounting for daylight savings

I am having a hard time converting a string representation of non-UTC times to UTC due to the timezone abbreviation.

(update: it seems that the timezone abbreviations may not be unique . if so, perhaps i should also be trying to take this into account. )

I've been trying to look for a way around this using datetutil and pytz, but haven't had any luck.

Suggestions or workaround would be appreciated.

string = "Jun 20, 4:00PM EDT" 

I'd like to convert that into UTC time, accounting for daylight savings when appropriate.

UPDATE: Found some references that may help more experienced users answer the Q.

Essentially, I would imagine part of the solution doing the reverse of this .

FINAL UPDATE (IMPORTANT)

Taken from the dateutil docs examples .

Some simple examples based on the date command, using the TZOFFSET dictionary to provide the BRST timezone offset.

parse("Thu Sep 25 10:36:28 BRST 2003", tzinfos=TZOFFSETS) datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzoffset('BRST', -10800))

parse("2003 10:36:28 BRST 25 Sep Thu", tzinfos=TZOFFSETS) datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzoffset('BRST', -10800))

Combine this with a library such as found here. and you will have a solution to this problem.

Using Nas Banov's excellent dictionary mapping timezone abbreviations to UTC offset:

import dateutil
import pytz

# timezone dictionary built here: https://stackoverflow.com/a/4766400/366335
# tzd = {...}

string = 'Jun 20, 4:00PM EDT'
date = dateutil.parser.parse(string, tzinfos=tzd).astimezone(pytz.utc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM