目次
1. Use datetime with zoneinfo (Python 3.9+)
2. For older Python versions (3.6–3.8): Use pytz
3. Work in UTC internally
4. Parse and format timezone-aware strings
Key Tips
ホームページ バックエンド開発 Python チュートリアル Pythonでタイムゾーンを使用する方法は?

Pythonでタイムゾーンを使用する方法は?

Aug 05, 2025 pm 04:53 PM
python タイムゾーン

Use zoneinfo for Python 3.9+ to create timezone-aware datetimes and convert between timezones with astimezone(); 2. For Python 3.6–3.8, use pytz with localize() to avoid DST errors; 3. Always work in UTC internally and convert to local time only for display; 4. Parse timezone-aware strings using fromisoformat() or dateutil.parser, and avoid naive and aware datetime comparisons, ensuring consistent, unambiguous time handling in applications.

How to work with timezones in Python?

Working with timezones in Python can be tricky, but with the right tools and understanding, it becomes manageable. The key is to always be aware of whether your datetime objects are naive (no timezone info) or aware (include timezone info), and to convert between timezones safely.

Here’s how to handle timezones properly in Python:


1. Use datetime with zoneinfo (Python 3.9+)

The modern and recommended way is to use the built-in zoneinfo module (available in Python 3.9+). It uses the IANA timezone database and doesn’t require external libraries.

from datetime import datetime
from zoneinfo import ZoneInfo

# Create a datetime with a specific timezone
local_time = datetime(2024, 4, 5, 12, 0, 0, tzinfo=ZoneInfo("America/New_York"))
print(local_time)  # 2024-04-05 12:00:00-04:00

# Convert to another timezone
utc_time = local_time.astimezone(ZoneInfo("UTC"))
print(utc_time)  # 2024-04-05 16:00:00+00:00

# Get current time in a timezone
now_in_london = datetime.now(ZoneInfo("Europe/London"))
print(now_in_london)

⚠️ Always use astimezone() to convert between timezones, not just assigning tzinfo.


2. For older Python versions (3.6–3.8): Use pytz

If you're on Python < 3.9, install and use pytz:

pip install pytz
from datetime import datetime
import pytz

# Define a timezone
tz_ny = pytz.timezone("America/New_York")

# Localize a naive datetime (correct way)
naive = datetime(2024, 4, 5, 12, 0, 0)
local_time = tz_ny.localize(naive)
print(local_time)  # 2024-04-05 12:00:00-04:00

# Convert to UTC
utc_time = local_time.astimezone(pytz.UTC)
print(utc_time)  # 2024-04-05 16:00:00+00:00

❗ Never do datetime(2024, 4, 5, 12, 0, tzinfo=tz_ny) — always use .localize() to avoid DST errors.


3. Work in UTC internally

Best practice: store and compute all timestamps in UTC, then convert to local time only for display.

from datetime import datetime
from zoneinfo import ZoneInfo

# Store time in UTC
utc_now = datetime.now(ZoneInfo("UTC"))

# Convert to user's timezone when displaying
user_tz = ZoneInfo("Asia/Tokyo")
japan_time = utc_now.astimezone(user_tz)
print(f"Current time in Tokyo: {japan_time}")

This avoids ambiguity, especially around daylight saving transitions.


4. Parse and format timezone-aware strings

Use strptime carefully — it may create naive datetimes.

from datetime import datetime
from zoneinfo import ZoneInfo

# Parsing ISO format with timezone
date_str = "2024-04-05T12:00:00+02:00"
dt = datetime.fromisoformat(date_str)
print(dt.tzinfo)  # Offset attached

# Or parse and assign timezone
raw_str = "2024-04-05 10:00:00"
naive = datetime.strptime(raw_str, "%Y-%m-%d %H:%M:%S")
aware = naive.replace(tzinfo=ZoneInfo("Europe/Paris"))

For more complex parsing, consider dateutil:

pip install python-dateutil
from dateutil import parser

dt = parser.parse("2024-04-05 10:00:00 EST")
print(dt)  # Already timezone-aware

Key Tips

  • Always prefer aware datetime objects in production.
  • Never compare naive and aware datetimes — it raises errors in Python 3.9+.
  • Use standard timezone names like America/Los_Angeles, not abbreviations like PST (they’re ambiguous).
  • Be careful with DST: .localize() and .astimezone() handle it correctly; direct tzinfo= does not.

Basically, use zoneinfo if you can, work in UTC, and always be explicit about timezones. It’s not hard once you get the pattern down.

以上がPythonでタイムゾーンを使用する方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Pythonで仮想環境を作成する方法 Pythonで仮想環境を作成する方法 Aug 05, 2025 pm 01:05 PM

Python仮想環境を作成するには、VENVモジュールを使用できます。手順は次のとおりです。1。プロジェクトディレクトリを入力して、python-mvenvenv環境を実行して環境を作成します。 2。SourceENV/bin/Activate to Mac/LinuxおよびEnv \ Scripts \ Windowsにアクティブ化します。 3. PIPINSTALLインストールパッケージ、PIPFREEZE> RECUMESSION.TXTを使用して、依存関係をエクスポートします。 4.仮想環境をGITに提出しないように注意し、設置中に正しい環境にあることを確認してください。仮想環境は、特にマルチプロジェクト開発に適した競合を防ぐためにプロジェクト依存関係を分離でき、PycharmやVSCodeなどの編集者も

PythonでSQLクエリを実行する方法は? PythonでSQLクエリを実行する方法は? Aug 02, 2025 am 01:56 AM

対応するデータベースドライバーをインストールします。 2。CONNECT()を使用してデータベースに接続します。 3.カーソルオブジェクトを作成します。 4。Execute()またはexecuteMany()を使用してSQLを実行し、パラメーター化されたクエリを使用して噴射を防ぎます。 5。Fetchall()などを使用して結果を得る。 6。COMMING()は、変更後に必要です。 7.最後に、接続を閉じるか、コンテキストマネージャーを使用して自動的に処理します。完全なプロセスにより、SQL操作が安全で効率的であることが保証されます。

Pythonの複数のプロセス間でデータを共有する方法は? Pythonの複数のプロセス間でデータを共有する方法は? Aug 02, 2025 pm 01:15 PM

MultiProcessing.Queueを使用して、複数のプロセスと消費者のシナリオに適した複数のプロセス間でデータを安全に渡す。 2。MultiProcessing.Pipeを使用して、2つのプロセス間の双方向の高速通信を実現しますが、2点接続のみ。 3.値と配列を使用して、シンプルなデータ型を共有メモリに保存し、競争条件を回避するためにロックで使用する必要があります。 4.マネージャーを使用して、リストや辞書などの複雑なデータ構造を共有します。これらは非常に柔軟ですが、パフォーマンスが低く、複雑な共有状態を持つシナリオに適しています。データサイズ、パフォーマンス要件、複雑さに基づいて適切な方法を選択する必要があります。キューとマネージャーは、初心者に最適です。

Python boto3 S3アップロード例 Python boto3 S3アップロード例 Aug 02, 2025 pm 01:08 PM

BOTO3を使用してファイルをS3にアップロードしてBOTO3を最初にインストールし、AWS資格情報を構成します。 2。boto3.client( 's3')を介してクライアントを作成し、upload_file()メソッドを呼び出してローカルファイルをアップロードします。 3. S3_Keyをターゲットパスとして指定し、指定されていない場合はローカルファイル名を使用できます。 4. filenotfounderror、nocredentialserror、clienterrorなどの例外を処理する必要があります。 5。ACL、ContentType、StorageClass、Metadataは、exrceargsパラメーターを介して設定できます。 6。メモリデータについては、bytesioを使用して単語を作成できます

Pythonのリストを使用してスタックデータ構造を実装する方法は? Pythonのリストを使用してスタックデータ構造を実装する方法は? Aug 03, 2025 am 06:45 AM

pythonlistscani実装Append()penouspop()popoperations.1.useappend()2つのBelief stotetopthestack.2.usep op()toremoveandreturnthetop要素、保証済みのtocheckeckeckestackisnotemptoavoidindexerror.3.pekattehatopelementwithstack [-1]

Pythonスケジュールライブラリの例 Pythonスケジュールライブラリの例 Aug 04, 2025 am 10:33 AM

Pythonscheduleライブラリを使用して、タイミングタスクを簡単に実装します。まず、PipinstallScheduleを介してライブラリをインストールし、スケジュールモジュールと時間モジュールをインポートし、定期的に実行する必要がある関数を定義し、スケジュールを使用して時間間隔を設定してタスク関数を結合します。最後に、スケジュールを呼び出してください。たとえば、10秒ごとにタスクを実行すると、スケジュールとして記述できます。すべて(10).seconds.do(job)。数分、数時間、日、週などをサポートし、特定のタスクを指定することもできます。

崇高なテキストでPythonコードを実行する方法 崇高なテキストでPythonコードを実行する方法 Aug 04, 2025 pm 04:25 PM

Ensurepythonisinstaledaddeddeddeddeddeddeddeddedtopathion interminal;

Pythonでメモリリークをデバッグするための一般的な戦略は何ですか? Pythonでメモリリークをデバッグするための一般的な戦略は何ですか? Aug 06, 2025 pm 01:43 PM

USETRACEMALLOCTOTRACKMEMORYALLOCATIONS ANDIDENTIFIFYMEMORYLINES; 2.monitorObjectCountSwithgcandobjgraphtodectectgrowingObjecttypes;

See all articles