This article introduces how to use the datetime
module and zoneinfo
module in Python 3.6 and above versions. Without a third -party library pytz
and dateutil
, you can easily realize the conversion of the date time of different time zones.
Core method: Use the method of the datetime
object. astimezone
Create the
datetime
Use the method to convert the date time into the target time zone. astimezone
Prerequisites: python & gt; = 3.6
TZData (Windows system and certain special environments may need to be installed)If the output is an empty set
, you need to install:
<code class="language-bash">python3 -c '__import__("zoneinfo").available_timezones()'</code>
Detailed steps and examples: set()
tzdata
<code class="language-bash">pip install tzdata</code>
Get the current time and specify the time zone:
Use the method, and specify the datetime
parameter as to get local time.
datetime.now()
Use the tz
construct function, and specify the ZoneInfo("localtime")
parameter. <code class="language-python">from datetime import datetime from zoneinfo import ZoneInfo dt = datetime.now(tz=ZoneInfo("localtime"))</code>
datetime
parameter. tzinfo
<code class="language-python">dt = datetime(2025, 1, 1, 0, 0, tzinfo=ZoneInfo("Europe/Istanbul"))</code>
datetime.fromtimestamp()
objects into target time zones. tz
<code class="language-python">unix_time = 1675000000 # 示例UNIX时间戳 dt = datetime.fromtimestamp(unix_time, tz=ZoneInfo("UTC"))</code>
astimezone
The output results are similar:
astimezone()
datetime
Through the above steps, you can easily use the Python native module to complete the conversion of the dated time in different time zones without relying on the additional third -party library. Remember to choose the appropriate method of creating the
<code class="language-python">pst = dt.astimezone(ZoneInfo("US/Pacific"))</code>
The above is the detailed content of [Python] How to convert different time zones without using pytz, dateutil. For more information, please follow other related articles on the PHP Chinese website!