Pythonの現在の日付と時刻

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

from datetime import datetime

# ローカルシステムの現在の日付時刻
print(datetime.now())

出力:2018-09-12 14:17:56.456080

Python現在の日付

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

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

出力:2018-09-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モジュールよりも高速です。Pendulumモジュールは、次のPIPコマンドを使用してインストールできます。

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の例をチェックアウトできます。

Source:
https://www.digitalocean.com/community/tutorials/python-current-date-time