2

My host has timezone UTC and I am trying to convert PDT time string to date time object, I have used the below given code-snippet but it didn't worked

datetime_obj = datetime.datetime.strptime('Thu Jun 09 08:28:12 PDT 2016', '%a %b %d %H:%M:%S %Z %Y')

I am getting this error -

ValueError: time data 'Thu Jun 09 08:28:12 PDT 2016' does not match format '%a %b %d %H:%M:%S %Z %Y'

I got it that it's because my host's timezone is UTC. But I am not able to figure out the way to solve this issue. I need to convert PDT string to UTC aware timezone.

I am blocked. Any help Appreciated.

Bruce_Wayne
  • 1,564
  • 3
  • 18
  • 41

1 Answers1

1

You can have many different values in TZINFOS. Which will support your code not to fail if it encounters different timezones.

Parse the string then converting PDT datetime to UTC is explained below.

import pytz
import dateutil.parser
TZINFOS = { 'PDT': pytz.timezone('US/Pacific')}
datetime_obj = dateutil.parser.parse('Thu Jun 09 08:28:12 PDT 2016', tzinfos= TZINFOS)
print datetime_obj
datetime_in_utc = datetime_obj.astimezone(pytz.utc) # convert to UTC
print datetime_in_utc

And print pytz.all_timezones will give you all possible values.

Marlon Abeykoon
  • 11,927
  • 4
  • 54
  • 75