【Python】Python ~ 基本編 / 日付・日時あれこれ ~

■ はじめに

https://dk521123.hatenablog.com/entry/2019/10/14/121909

の続き。

テストデータなどを作るのに、日付の処理について扱ったのでメモ。

目次

【1】X日前の日付の取得
【2】日付でループさせる
【3】月初・月末の取得

【1】X日前の日付の取得

from datetime import datetime, timedelta

print(datetime.now().strftime('%Y%m%d')) # e.g. 20231031
three_days_ago = datetime.now() - timedelta(days=3)
print(three_days_ago.strftime('%Y%m%d')) # e.g. 20231028

参考文献
https://qiita.com/hayasisiki/items/0adf43e1b91487654a7b

【2】日付でループさせる

from datetime import date, timedelta

def date_range(start: date, stop: date, step = timedelta(1)):
  current = start
  while current <= stop:
    yield current
    current += step

for target_date in date_range(date(2022, 1, 25), date(2022, 2, 9)):
  result = target_date.strftime('%Y/%m/%d')
  print(result)

出力結果

2022/01/25
2022/01/26
2022/01/27
2022/01/28
2022/01/29
2022/01/30
2022/01/31
2022/02/01
2022/02/02
2022/02/03
2022/02/04
2022/02/05
2022/02/06
2022/02/07
2022/02/08
2022/02/09

参考文献
https://qiita.com/ground0state/items/508e479335d82728ef91

【3】月初・月末の取得

import datetime
import calendar

# 月初の取得
def get_beginning_of_month(target_date=datetime.datetime.now()):
  return target_date.replace(
    day=1, hour=0, minute=0, second=0, microsecond=0)
# 月末の取得
def get_end_of_month(target_date=datetime.datetime.now()):
  end_day = calendar.monthrange(target_date.year, target_date.month)[1]
  return target_date.replace(
    day=end_day, hour=23, minute=59, second=59, microsecond=999999)

# 2021-02-01 00:00:00
print(get_beginning_of_month())
# 2021/02/01
print(get_beginning_of_month().strftime('%Y/%m/%d'))

# 2021-02-28 23:59:59.999999
print(get_end_of_month())
# 2021/02/28
print(get_end_of_month().strftime('%Y/%m/%d'))

別解

beginning_of_month = target_date.replace(day=1)
print(datetime.strftime(beginning_of_month, '%Y-%m-%d'))

参考文献
https://note.nkmk.me/python-datetime-first-last-date-last-week/
https://huge.mints.ne.jp/02/2016/it_technique/1708/

関連記事

Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 基本編 / 日付・日時 ~
https://dk521123.hatenablog.com/entry/2019/10/14/121909