from datetime import datetime, timedelta
# 時刻の取得
nw = datetime.now()
print(nw)
print(f'Year: {nw.year}')
print(f'Month: {nw.month}')
print(f'Day: {nw.day}')
print(f'Hour: {nw.hour}')
print(f'Minute: {nw.minute}')
print(f'Second: {nw.second}')
print(f'Microsecond: {nw.microsecond}')
# 時刻を生成する
the_date = datetime(2020, 4, 1, 9, 0, 0)
print(f'date_created: {the_date}')
# 文字列から時刻を生成する
str_date1 = '2022/12/24 23:59:59'
st1 = datetime.strptime(str_date1, "%Y/%m/%d %H:%M:%S")
print(f'from_text(/): {st1}')
str_date2 = '2022年12月24日 23時59分59秒'
st2 = datetime.strptime(str_date2, '%Y年%m月%d日 %H時%M分%S秒')
print(f'from_text(和): {st2}')
# datetimeから文字列に変換する
dt = datetime(2020, 4, 1, 9, 0, 0)
print(f'{dt:%Y/%m/%d %H:%M:%S}')
# 時間の計算 (days=xxx)
newyear_day = datetime(2022, 1, 1)
print(f'NewYear: {newyear_day}')
endyear_day = newyear_day + timedelta(days=364)
print(f'EndYear: {endyear_day}')
first_quarter = newyear_day + timedelta(days=+90)
print(first_quarter)
diff = endyear_day - newyear_day
print(f'{diff}日')
# datetime を比較する
# the_day2の200日後が、somedayの日付より前か後ろかを判別
the_day2 = datetime(2022, 1, 1)
some_day2 = datetime(2022, 8, 1)
# 2022年1月1日の200日後を計算
after_200 = the_day2 + timedelta(days=200)
# 比較
if after_200 < some_day2:
print(f'{after_200:%Y/%m/%d}は、2022/08/01より前です')
else:
print(f'{after_200:%Y/%m/%d}は、2022/08/01以降です')