Skip to content

datetime & time#

from datetime import datetime, timedelta

past = datetime.now() - timedelta(days=1)
now = datetime.now()

print(now > past)
import datetime

old = datetime.date(2020, 1, 1)
latest = datetime.date(2022, 1, 1)

print(lates > old)

datetime オブジェクトから文字列取得#

from datetime import datetime

datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# '2022-06-06 22:31:49'

time モジュールで現在の時刻を取得する

import time
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
# '2022-06-06 22:32:57'

文字列から datetime オブジェクト作成#

from datetime import datetime

datetime.strptime("2022-01-01", "%Y-%m-%d")
# datetime.datetime(2022, 1, 1, 0, 0)

昨日、今日、明日#

from datetime import datetime, timedelta

nowadays = datetime.now()
yesterday = nowadays - timedelta(1)
tomorrow = nowadays + timedelta(1)

print("昨日の日付は ",yesterday.strftime('%d-%m-%Y'))
print("今日の日付は ",nowadays.strftime('%d-%m-%Y'))
print("昨日の日付は ",tomorrow.strftime('%d-%m-%Y'))

月、曜日の取得#

from datetime import datetime

print(datetime.now().strftime('%A, %a, %B, %b'))