4

I have a tedious function that does something like this:

...
if ('PDT' in stringVal) or ('PST' in stringVal):
    utcdateTime = convert(stringVal)+(hardcode the offset)
elif('EDT' in stringVal)...
...

I looked at several posts including this but couldn't find anything that fits my purpose. I also looked at datetime.datetime and the whole datetime module in general but it has things like .now(); .utcnow(); datetime.now(tz.pytz.utc) etc etc. Basically if I have something like:

2014-05-01 01:02:03 PDT
2014-05-01 01:02:03 PST
2014-05-01 01:02:03 EDT
2014-05-01 01:02:03 EST
2014-05-01 01:02:03 MDT
2014-05-01 01:02:03 MST

Is there a python module that has some method I can use to convert those above datetime strings to UTC? If there is none, I will just stick with the hard-coded way I have.

Nikhil Gupta
  • 551
  • 10
  • 28
  • 1
    Not exactly a duplicate, but a similar / inverse problem. You should find how to parse timezones and convert from local to utc in the answers. – viraptor Apr 13 '16 at 00:38
  • 1
    Neither of those seem to be duplicates, one doesn't deal with timezones, and the other is doing the reverse, converting from UTC – Brendan Abel Apr 13 '16 at 00:38
  • @BrendanAbel The reverse is not really the reverse. You're using `.astimezone(...)` with timezone as a parameter. Surely if you can write any Python at all, you can generalise that answer. – viraptor Apr 13 '16 at 03:10
  • @AkshatMahajan Clearly not a duplicate of what you posted – Nikhil Gupta Apr 13 '16 at 14:56
  • @viraptor I am going to try the solution in that post. Not a duplicate but something similar. I will try their way – Nikhil Gupta Apr 13 '16 at 14:57

1 Answers1

2

You'll need to translate the timezone strings, but otherwise you can use the datetime and pytz libraries.

import datetime
import pytz

s = '2014-05-01 01:02:03 PST'
ds, tzs = s.rsplit(' ', 1)

tz_map = {
    'PST': 'US/Pacific', 
    'EST': 'US/Eastern'
}
tz = pytz.timezone(tz_map[tzs])

dt = datetime.datetime.strptime(ds, '%Y-%m-%d %H:%M:%S').replace(tzinfo=tz)
dt_utc = dt.astimezone(pytz.utc)
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118