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.

5
  • 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. Commented Apr 13, 2016 at 0: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 Commented Apr 13, 2016 at 0: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. Commented Apr 13, 2016 at 3:10
  • @AkshatMahajan Clearly not a duplicate of what you posted Commented Apr 13, 2016 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 Commented Apr 13, 2016 at 14:57

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

5 Comments

On line 5 there is an error: splitting by ' ' will result in three values being returned, not two.
Thanks, there was supposed to be a 1 as the second arg.
@BrendanAbel how would this handle "PDT" and "EDT" etc?
They use the same timezone as PST, EST. Pytz will use the correct one based on the date. If you actually want to force PDT during a PST date, you can use timezone.localize with a PDT date to get a static PDT timezone.
@BrendanAbel I tried using your code which works great but when I used "PDT" in the string, the UTC time was off by an hour.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.