Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 415
snakesNbronies Avatar asked Jun 21 '12 17:06

snakesNbronies


1 Answers

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)
like image 86
Bryan Avatar answered Sep 22 '22 14:09

Bryan