36
43

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.

【Python】日付をforで回したい (〇月〇日から△月△日まで〜)

Posted at

はじめに

〇月〇日から△月△日まで〜 みたいなのをforで回したい時ありますよね。

そんな時に使えそうなライブラリを作ったので投稿します。

ソースコード

名前は dt-range めっちゃ普通。

使い方

まずは普通に pip を使ってインストール

$ pip install dt-range

週単位で回したいとき: weekrange

from datetime import datetime

from dt_range import weekrange

START = datetime(2021, 1, 1)
END = datetime(2021, 1, 31)

for dt in weekrange(START, END):
    print(dt)
# 2021-01-01 00:00:00
# 2021-01-08 00:00:00
# 2021-01-15 00:00:00
# 2021-01-22 00:00:00
# 2021-01-29 00:00:00

for dt in weekrange(START, END, weeks=2):
    print(dt)
# 2021-01-01 00:00:00
# 2021-01-15 00:00:00
# 2021-01-29 00:00:00

日単位で回したいとき: daterange

from datetime import datetime

from dt_range import daterange

START = datetime(2021, 1, 1)
END = datetime(2021, 1, 31)

for dt in daterange(START, END):
    print(dt)
# 2021-01-01 00:00:00
# 2021-01-02 00:00:00
# 2021-01-03 00:00:00
# ...
# 2021-01-29 00:00:00
# 2021-01-30 00:00:00
# 2021-01-31 00:00:00


for dt in daterange(START, END, days=4):
    print(dt)
# 2021-01-01 00:00:00
# 2021-01-05 00:00:00
# 2021-01-09 00:00:00
# 2021-01-13 00:00:00
# 2021-01-17 00:00:00
# 2021-01-21 00:00:00
# 2021-01-25 00:00:00
# 2021-01-29 00:00:00

時間単位で回したいとき

from datetime import datetime

from dt_range import hourrange

START = datetime(2021, 1, 1)
END = datetime(2021, 1, 1, 23)

for dt in hourrange(START, END):
    print(dt)
# 2021-01-01 00:00:00
# 2021-01-01 01:00:00
# 2021-01-01 02:00:00
# 2021-01-01 03:00:00
# ...
# 2021-01-01 21:00:00
# 2021-01-01 22:00:00
# 2021-01-01 23:00:00

for dt in hourrange(START, END, hours=4):
    print(dt)
# 2021-01-01 00:00:00
# 2021-01-01 04:00:00
# 2021-01-01 08:00:00
# 2021-01-01 12:00:00
# 2021-01-01 16:00:00
# 2021-01-01 20:00:00

あとは、minuterange (分単位)secondrange (秒単位), millisecondrange (ミリ秒単位), microsecondrange (マイクロ秒単位) などがあります。

timdelta を使用して回すことも

from datetime import datetime, timedelta

from dt_range import timedeltarange

START = datetime(2021, 1, 1)
END = datetime(2021, 1, 31)

for dt in timedeltarange(
    START,
    END,
    timedelta(days=5, hours=4, minutes=3, seconds=2, microseconds=1),
):
    print(dt)
# 2021-01-01 00:00:00
# 2021-01-06 04:03:02.000001
# 2021-01-11 08:06:04.000002
# 2021-01-16 12:09:06.000003
# 2021-01-21 16:12:08.000004
# 2021-01-26 20:15:10.000005

こんな細かいの絶対使わんやろ

最後に

またつまらぬものを作ってしまった。

36
43
3

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
36
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?