0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

日付(文字列型)をリストにして返す関数

Last updated at Posted at 2021-02-27

for文で回したいときにどうぞ。

from datetime import timedelta
from datetime import datetime as dt

def datelist(start_str="2018-1-1", end_str="2018-12-31", input_format='%Y-%m-%d', output_format='%Y-%m-%d') -> list:
    """指定した日付から日付までの日付(文字列型)をリストにまとめて返す。
    日付型で返したいときは`.strftime(output_format)`を削除すればOK。
    end_strに指定した日付も含まれる。
    引数のinput_format, output_formatはdatetime.strftimeで利用する形式"""
    start_dt = dt.strptime(start_str, input_format)
    end_dt = dt.strptime(end_str, input_format)
    days_count = (end_dt - start_dt).days + 1 # 最終日も含めたいので、+1

    result = map(lambda x:
                 (start_date + timedelta(days=x)).strftime(output_format), range(days_count))
    return list(result) # ['2018-01-01', '2018-01-02',....]
def datelist_year(year=2000, output_format='%Y-%m-%d'):
    """1年分をまるごと出力"""
    start_date = dt.strptime('{}-1-1'.format(year), '%Y-%m-%d')
    end_date = dt.strptime('{}-12-31'.format(year), '%Y-%m-%d')
    days_count = (end_date - start_date).days + 1 # 最終日も含めたいので、+1

    result = map(lambda x:
                 (start_date + timedelta(days=x)).strftime(output_format), range(days_count))
    return list(result) # ['2000-01-01', '2000-01-02',....]
def datelist_month(year=2000, month=1, output_format='%Y-%m-%d'):
    """1か月分をまるごと出力"""
    start_date = dt.strptime('{}-{}-1'.format(year, month), '%Y-%m-%d')
    if int(month) < 12:
        next_month = int(month)+1
        end_date = dt.strptime('{}-{}-1'.format(year, next_month), '%Y-%m-%d')
    else:
        next_year = int(year) + 1
        end_date = dt.strptime('{}-{}-1'.format(next_year, '1'), '%Y-%m-%d')
    days_count = (end_date - start_date).days

    result = map(lambda x:
                 (start_date + timedelta(days=x)).strftime(output_format), range(days_count))
    return list(result) # ['200-01-01', '2000-01-02',....]
# おまけ。年と月の組み合わせのリストを返す。上のやつと組み合わせて使うことを想定している。
def monthlist(start_year, start_month, end_year, end_month):
    result = []
    
    # 引数がおかしい時は空のリストを返す
    if start_year > end_year:
        return []
    # その年だけの場合
    elif start_year == end_year:
        # 引数がおかしい時は空のリストを返す
        if start_month > end_month:
            return []
        # 正常系
        for month in range(start_month, end_month+1):
            combination = [year, month]
            result.append(combination)
        return result
    # 2年以上の場合
    else:
        # 最初の年
        for month in range(start_month, 13):
            combination = [start_year, month]
            result.append(combination)
        # 中間の年(3年以上の場合だけ通る)
        if start_year + 2 <= end_year: 
            for year in range(start_year+1, end_year):
                for month in range(1,13):
                    combination = [year, month]
                    result.append(combination)
        # 最後の年
        for month in range(1, end_month):
            combination = [end_year, month]
            result.append(combination)
        return result

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?