Python: how to correctly convert from a string date in a particular time zone?
<p>I have input from a human in <code>YYYY-MM-DD HH:MM:SS</code> format that I know is supposed to be Los Angeles local time. In Python, how do I convert this to a <code>datetime.datetime</code> object that is unambiguous and correct? I am aware that the input is ambiguous during the autumn transition out of DST; I'm fine with either choice happening for dates within that hour as long as it is deterministic.</p>

<p>Here is my attempt, which I'm surprised to find doesn't work:</p>

<pre><code>&gt;&gt;&gt; import pytz
&gt;&gt;&gt; from dateutil import parser as date_parser
&gt;&gt;&gt; PACIFIC = pytz.timezone('US/Pacific')
&gt;&gt;&gt; result = date_parser.parse('2016-08-01 00:00:00 FOO', tzinfos={'FOO': PACIFIC})
&gt;&gt;&gt; result.utcoffset()
datetime.timedelta(-1, 57600)
&gt;&gt;&gt; str(result)
'2016-08-01 00:00:00-08:00'
</code></pre>

<p>Despite having asked for <code>US/Pacific</code> and this being a summer date, I get UTC-8 instead of UTC-7.</p>

<p>I found <a href="https://artofsoftware.org/2012/04/17/dealing-with-daylight-savings-time-using-pytz/" rel="nofollow">This</a>, which may help. Chopping it up a bit, I got the -0700 that you're looking for. I have to admit I don't understand this module, so I can't point to where you can fix your code quickly (and I don't use python on the command line much,) but the below works.</p>

<pre><code>import datetime
import pytz

def report(time):
    mytz = pytz.timezone('US/Pacific')
    dtformat = "%Y-%m-%d %H:%M"
    t = datetime.datetime.strptime(time, dtformat).replace(tzinfo=pytz.utc)
    print ("*****")
    print (t)
    print (mytz.normalize(t))

report("2011-08-01 00:00")
</code></pre>

<p>So, hope this helps!</p>

python datetime python-datetime python-dateutil