Why is this code dependant on my local machine timezone?
<p>Why does this code:</p>

<pre><code>def parse_date(datetime_string, tz_code):
    tz = timezone(tz_code)
    datetime_obj = parser.parse(datetime_string)
    datetime_obj_localized = datetime_obj.replace(tzinfo=tz)
    return time.mktime(datetime_obj_localized.timetuple())


def test_parse_date(self):
   self.assertEquals(1482951600, parse_date('2016-12-28 14:00', 'US/Eastern')
</code></pre>

<p>returns a different value depending on the timezone of the machine it is running on?</p>

<p>In my understanding, the parser returns a datetime without a timezone, it then assign a tz, without changing anything else and finally it is converted into a timestamp. My local tz should not be used anywhere.</p>

<p><code>dateutil.parser</code> will attach a time zone if and only if it finds one, which <em>could</em> depend on your local machine time zone settings, because if it detects an abbreviated time zone like "EST" that is in the list of abbreviations for your local time zone, it will assume that that's the one you mean.</p>

<p>That said, this is not what is happening in this case. Even if <code>parser</code> were attaching a time zone, <code>datetime.replace</code> does a wholesale replacement of the time zone, not a conversion. I do not think there is enough information in your question to fully diagnose this issue, but if <code>timezone()</code> is <code>pytz.timezone()</code>, at least one of your issues is that <code>pytz</code> time zones can't be attached to <code>datetime</code> objects with <code>replace</code>. You would need to instead use <code>datetime_obj = pytz.timezone(tz_code).localize(datetime_obj)</code>.</p>

<p>Note that the <code>localize</code> method assumes that you have a timezone-naive object, so it will throw an error if <code>datetutil</code>'s parser returns a timezone-aware <code>datetime</code>, so you should pass <code>ignoretz=True</code> to the parser to prevent this.</p>

<p>That said, even once you do this, the real issue is in your use of <code>time.mktime</code>. See <a href="https://stackoverflow.com/questions/38963653/dateutil-parse-bug-in-python-returns-the-wrong-value/38964103#38964103">this answer</a>, which is exactly the same problem. To summarize that answer, the best thing to do is to use <code>calendar.timegm</code> instead of <code>mktime</code>, and convert to UTC before calling it. Incorporating my suggestions, here is an updated version of your code:</p>

<pre><code>import calendar
from dateutil.tz import tzutc

def parse_date(datetime_string, tz_code):
    tz = timezone(tz_code)
    datetime_obj = parser.parse(datetime_string, ignoretz=True)
    datetime_obj_localized = tz.localize(datetime_obj)

    datetime_obj_utc = datetime_obj_localized.astimezone(tzutc())
    return calendar.timegm(datetime_obj_utc.timetuple())
</code></pre>

python timezone python-dateutil