擅长:python、mysql、java
<p>这只是将时间戳解析为您提供的tz(因此它假定<code>dt</code>是本地时间)。如果<code>dt</code>是绝对/UTC,并且要将其转换为本地时区,则需要首先将其解析为UTC datetime,然后移动其时区:</p>
<pre class="lang-py prettyprint-override"><code>datetime.fromtimestamp(timestamp, pytz.utc).astimezone(pytz.timezone('America/Sao_Paulo'))
</code></pre>
<p>例如,使用<a href="https://www.unixtimeconverter.io/1234567890" rel="nofollow noreferrer">1234567890</a>:</p>
<pre class="lang-py prettyprint-override"><code>>>> datetime.fromtimestamp(ts, pytz.utc)
datetime.datetime(2009, 2, 13, 23, 31, 30, tzinfo=<UTC>)
>>> datetime.fromtimestamp(ts, pytz.utc).astimezone(pytz.timezone('America/Sao_Paulo'))
datetime.datetime(2009, 2, 13, 21, 31, 30, tzinfo=<DstTzInfo 'America/Sao_Paulo' -02-1 day, 22:00:00 DST>)
</code></pre>
<p>还要注意,由于各种历史原因,正确使用pytz并不像(<a href="https://stackoverflow.com/questions/1422880/pytz-why-is-normalize-needed-when-converting-between-timezones">e.g.</a>)那样简单。如果你要经常处理时区,你可能想看看<em>钟摆</em>,它试图使时区操作更可靠,并提供一个更友好的API</p>