環境設定 数値 文字列 正規表現 リスト タプル 集合 辞書 ループ 関数 クラス データクラス 時間 パス ファイル スクレイピング その他

Pythonで現在時刻や今日の日付を表示する:datetimeを使って昨日と明日の日付も計算してみよう

最終更新日 2023.02.18

Python で今日の日付を取得するときは date の today 関数を使います。現在の時刻は datetime の today 関数で取得します。どちらも datetime というライブラリを使っているので、最初に datetime をインポートしてください。

import datetime

today = datetime.date.today()
now = datetime.datetime.today()

print(today)  # 2018-03-12
print(now)  # # 2018-03-12 15:11:44.342740

現在時刻の取得で datetime が二つ重なっていますが、間違いではありません。日付も時刻もハイフンで区切られています。

Python で今日の年、月、日をそれぞれ取得する

上のコードではハイフンつきの年月日を取得していますが、日にちだけを整数値として取りだしたいなどは、次のようにします。

import datetime

today = datetime.date.today()

year = today.year
month = today.month
day = today.day

print(year)  # 2018
print(month)  # 3
print(day)  # 12

today 関数で取得した「今日の日付」は date オブジェクトであり、年月日をそれぞれフィールドとして持ちます。

Python で現在の時刻から時間、分、秒をそれぞれ取得する

import datetime

now = datetime.datetime.today()

year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
microsecond = now.microsecond

print(year)  # 2018
print(month)  # 3
print(day)  # 12
print(hour)  # 15
print(minute)  # 24
print(second)  # 2
print(microsecond)  # 52716

Python で明日と昨日の日時を取得する

datetime の datetime で今日の日時をまずは取得します。今日の datetime オブジェクトに datetime の timedelta を加減して、明日と昨日の datetime オブジェクトを計算します。

import datetime

today = datetime.datetime.today()

print(today)  # 2019-11-26 14:49:47.623516
print(type(today))  # <class 'datetime.datetime'>

tomorrow = today + datetime.timedelta(days=1)
yesterday = today - datetime.timedelta(days=1)

print(tomorrow)  # 2019-11-27 14:49:47.623516
print(yesterday)  # 2019-11-25 14:49:47.623516

print(type(tomorrow))  # <class 'datetime.datetime'>

datetime オブジェクトから年月日を取得することは簡単です。

print(tomorrow.year)  # 2019
print(tomorrow.month)  # 11
print(tomorrow.day)  # 27

これらの例からわかるように、日時の計算は datetime オブジェクトが中心です。