In Python, how to get a localized timestamp with only the datetime package?
<p>I have a unix timestamp in seconds (such as <code>1294778181</code>) that I can convert to UTC using </p>

<pre><code>from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)
</code></pre>

<p>Problem is, I would like to get the corresponding time in <code>'US/Eastern'</code> (considering any DST) and I cannot use <code>pypz</code> and other utilities. </p>

<p>Only <code>datetime</code> is available to me. </p>

<p>Is that possible?
Thanks!</p>

<p>Easiest, but not supersmart solution is using timedelta</p>

<pre><code>import datetime
&gt;&gt;&gt; now = datetime.datetime.utcnow()
</code></pre>

<p>US/Eastern is 5 hours behind UTC, so let's just create thouse five hours as a timedelta object and make it negative, so that when reading back our code we can see that the offset is -5 and that there's no magic to deciding when to add and when to subtract timezone offset</p>

<pre><code>&gt;&gt;&gt; eastern_offset = -(datetime.timedelta(hours=5))
&gt;&gt;&gt; eastern = now + eastern_offset
&gt;&gt;&gt; now
datetime.datetime(2016, 8, 26, 20, 7, 12, 375841)
&gt;&gt;&gt; eastern
datetime.datetime(2016, 8, 26, 15, 7, 12, 375841)
</code></pre>

<p>If we wanted to fix DST, we'd run the datetime through smoething like this (not entirely accurate, timezones are not my expertise (googling a bit now it changes each year, yuck)) </p>

<pre><code>if now.month &gt; 2 and now.month &lt; 12:
    if (now.month == 3 and now.day &gt; 12) or (now.month == 11 and now.day &lt; 5):
        eastern.offset(datetime.timedelta(hours=5))
</code></pre>

<p>You could go even into more detail, add hours, find out how exactly it changes each year... I'm not going to go through all that :)</p>

python datetime epoch python-datetime