日付の取得 操作
タイトル:pythonで日付処理
カテゴリ:python
投稿日:22/05/16 22:25
更新日:22/05/17 22:07
GOOD
0
お気に入り
pythonでの日付取得・操作について 。
まぁまぁ使いどころがあったので、残しときます。
```py:Sample.py
import datetime
from dateutil.relativedelta import relativedelta
def Sample():
# 現在時刻
today = datetime.datetime.today()
print(today)
# >>> 2022-05-16 22:20:06.956045
# 日付指定
happybirthday = datetime.datetime(2000,1,1,0,0,0)
print(happybirthday)
# >>> 2000-01-01 00:00:00
# 個別に取得
year = happybirthday.year
month = happybirthday.month
day = happybirthday.day
hour = happybirthday.hour
minute = happybirthday.minute
second = happybirthday.second
weekday = happybirthday.weekday()
print(f"年:{year}、月:{month}、日:{day}、時:{hour}、分:{minute}、秒:{second}")
# >>> 年:2000、月:1、日:1、時:0、分:0、秒:0
# 日付の計算
tomorrow = today + datetime.timedelta(days=1)
print(tomorrow)
# >>> 2022-05-17 22:20:06.956045
yesterday = today - datetime.timedelta(days=1)
print(yesterday)
# >>> 2022-05-15 22:20:06.956045
# 年 月の計算
next_year = today + relativedelta(years=1)
print(next_year)
# 2023-05-16 22:20:06.956045
last_month = today - relativedelta(months=1)
print(last_month)
# 2022-04-16 22:20:06.956045
if __name__ == "__main__":
Sample()
```