Python 現在の日付と時間
私たちはPythonのdatetimeモジュールを使って、ローカルシステムの現在の日付と時刻を取得できます。
from datetime import datetime
Current date time in local system
print(datetime.now())
2018-09-12 14:17:56.456080
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は、タイムゾーンの実装を取得するために使用できる人気のあるモジュールの一つです。このモジュールは、以下の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 ペンデュラム モジュール
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
完全なPythonスクリプトやその他のPythonの例は、私たちのGitHubリポジトリからチェックできます。
