【Python】日付操作サンプル

2023年6月3日PG,Python

Pythonによる日付操作のサンプル

今日の日付を表示する

  • 今日の日付をyyyymmdd形式で表示する
  • strftime() は日付、時間を文字列へ変換する関数
import datetime

today = datetime.datetime.today().strftime('%Y%m%d')

print(today)
  • 実行結果

20221229


昨日の日付を表示する

  • 日にちの加算で昨日の日付を表示する
import datetime

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

print(yesterday.strftime('%Y%m%d'))
  • 実行結果

20221228


先月末日を取得する1

  • 今日の年月日から今日の日数を引いて先月末日を求める
import datetime

today = datetime.datetime.today()
last_month = today - datetime.timedelta(days=today.day)

print(today)
print(last_month.strftime('%Y%m%d'))
  • 実行結果

2022-12-29 09:20:49.362141 20221130


先月末日を取得する2

  • calendar関数を使用して先月末日を取得する
  • calendar.monthrange(year, month) は年、月を引数として、その月初の曜日と日数を返す関数
  • ここでは日数しか必要ないので[1]を指定して変数daysに格納している
import calendar
import datetime
from dateutil import relativedelta

today = datetime.datetime.today()
last_month = today - relativedelta.relativedelta(months=1)
days = calendar.monthrange(last_month.year, last_month.month)[1]
last_month_day = datetime.date(last_month.year, last_month.month, days)

print(last_month_day)
  • 実行結果

2022-11-30


先月同日、翌月同日を取得する

  • relativedelta を使用すると容易に求められる
import datetime
from dateutil import relativedelta

today = datetime.datetime.today()
last_month = today - relativedelta.relativedelta(months=1)
next_month = today + relativedelta.relativedelta(months=1)

print(today)
print(last_month)
print(next_month)
  • 実行結果

2022-12-29 09:22:52.995856 2022-11-29 09:22:52.995856 2023-01-29 09:22:52.995856


平日か休日かを判定する

  • weekday() は月曜~日曜を0~6で返す関数
  • 返ってくる数字を調べて平日か休日かを判定する
  • strptime() は文字列から日付、時間へ変換する関数
from datetime import date
import datetime

def check_date(input_ymd):
    check_date = datetime.datetime.strptime(input_ymd, '%Y%m%d')

    yy = int(check_date.strftime('%Y'))
    mm = int(check_date.strftime('%m'))
    dd = int(check_date.strftime('%d'))

    if date(yy, mm, dd).weekday() < 5:
        date_result = '平日'
    else:
        date_result = '休日'

    return date_result

# --------------------
# メイン処理
# --------------------
input_ymd = '20221231'
print(check_date(input_ymd))
  • 実行結果

休日

PG,Python

Posted by junichi