search
HomeBackend DevelopmentPython Tutorial[Python] How to convert different time zones without using pytz, dateutil

No need to Pytz and Datemil, Python's native implementation of the dated time conversion of different time zones

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

Brief step:

Create the
    object containing the time zone information.
  1. datetime Use the method to convert the date time into the target time zone.
  2. astimezone Prerequisites:

python & gt; = 3.6

TZData (Windows system and certain special environments may need to be installed)
  • Check and install tzdata:
Run the following commands in the terminal or command prompt to check whether the necessary time zone data is installed in the system:

If the output is an empty set

, you need to install

:

python3 -c '__import__("zoneinfo").available_timezones()'

Detailed steps and examples: set() tzdata

<.> 1. Create
pip install tzdata
objects containing the time zone information:

Get the current time and specify the time zone:

Use the method, and specify the datetime parameter as to get local time.

  • Specify a specific date of time and time zone: datetime.now() Use the tz construct function, and specify the ZoneInfo("localtime") parameter.
from datetime import datetime
from zoneinfo import ZoneInfo

dt = datetime.now(tz=ZoneInfo("localtime"))
  • Convert from UNIX timestamp: Use the method, and specify the datetime parameter. tzinfo
dt = datetime(2025, 1, 1, 0, 0, tzinfo=ZoneInfo("Europe/Istanbul"))
<.> 2. Use
    Method conversion time zone:
  • Use the method to convert datetime.fromtimestamp() objects into target time zones. tz
Example:
unix_time = 1675000000  # 示例UNIX时间戳
dt = datetime.fromtimestamp(unix_time, tz=ZoneInfo("UTC"))
Converting Turkish Istanbul time on January 1, 2025 to 0:00 to Pacific Standard Time (PST).

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

object according to your actual needs.
pst = dt.astimezone(ZoneInfo("US/Pacific"))

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment