現在の日時を取得するためのPythonのコード

ローカルシステムの現在の日付と時刻を取得するために、Pythonのdatetimeモジュールを使用することができます。

from datetime import datetime

# Current date time in local system
print(datetime.now())

出力:2018年09月12日14時17分56.456秒

現在の日付のPython

もしローカルシステムの日付に興味がある場合は、datetimeのdate()メソッドを使用することができます。

print(datetime.date(datetime.now()))

出力: 2018年9月12日

Pythonの現在の時刻

ローカルのシステムで時間のみが欲しい場合は、datetimeオブジェクトを引数として渡すことでtime()メソッドを使用してください。

print(datetime.time(datetime.now()))

出力:14時19分46秒423440。

Pythonの現在の日付および時間をタイムゾーン(pytz)で取得する。

たいていの場合、私たちは他の人にも利用できるように、特定のタイムゾーンで日付が必要です。Pythonのdatetime now()関数は、tzinfo抽象ベースクラスの実装であるタイムゾーン引数を受け入れます。Pythonのpytzは、タイムゾーンの実装を取得するために使用できる人気のあるモジュールの1つです。以下のPIPコマンドを使用して、このモジュールをインストールできます。

pip install pytz

特定のタイムゾーンで時間を取得するためにpytzモジュールを使用するいくつかの例を見てみましょう。

import pytz

utc = pytz.utc
pst = pytz.timezone('America/Los_Angeles')
ist = pytz.timezone('Asia/Calcutta')

print('Current Date Time in UTC =', datetime.now(tz=utc))
print('Current Date Time in PST =', datetime.now(pst))
print('Current Date Time in IST =', datetime.now(ist))

結果:

Current Date Time in UTC = 2018-09-12 08:57:18.110068+00:00
Current Date Time in PST = 2018-09-12 01:57:18.110106-07:00
Current Date Time in IST = 2018-09-12 14:27:18.110139+05:30

すべてのサポートされているタイムゾーンの文字列を知りたい場合は、次のコマンドを使用してこの情報を印刷することができます。

print(pytz.all_timezones)

pytzモジュールによってサポートされているすべてのタイムゾーンのリストが表示されます。

Python Pendulumモジュール

Python Pendulumモジュールは、別のタイムゾーンライブラリであり、そのドキュメントによれば、pytzモジュールよりも高速です。以下のPIPコマンドを使用して、Pendulumモジュールをインストールすることができます。

pip install pendulum

pendulum.timezones属性から、サポートされているタイムゾーン文字列のリストを取得することができます。pendulumモジュールを使用して、異なるタイムゾーンで現在の日付と時刻情報を取得するいくつかの例を見てみましょう。

import pendulum

utc = pendulum.timezone('UTC')
pst = pendulum.timezone('America/Los_Angeles')
ist = pendulum.timezone('Asia/Calcutta')

print('Current Date Time in UTC =', datetime.now(utc))
print('Current Date Time in PST =', datetime.now(pst))
print('Current Date Time in IST =', datetime.now(ist))

出力:

Current Date Time in UTC = 2018-09-12 09:07:20.267774+00:00
Current Date Time in PST = 2018-09-12 02:07:20.267806-07:00
Current Date Time in IST = 2018-09-12 14:37:20.267858+05:30

弊社のGitHubリポジトリでは、完全なPythonスクリプトや他のPythonの例を入手することができます。

コメントを残す 0

Your email address will not be published. Required fields are marked *