2
6

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 で「年月」を扱う

Last updated at Posted at 2020-07-06

Python で「年月」を扱うためのクラスを書いたが、dateutil を使えばできるということに後から気付いてしまったので供養。勢いで書いたし テストもないので (最低限のテストは書いたが) 使うときは自己責任で。

実装

PyPI に上げたので、pip でインストールできる。

$ pip install ym

コードはこちら
https://github.com/hoto17296/python-ym

用例

from ym import ym

年月を指定してインスタンス作成

ym(2020, 4)  #=> ym(2020, 4)

現在の月からインスタンス作成

ym.current()  #=> ym(2020, 7)

文字列からインスタンス作成

ym.parse("2020-04")  #=> ym(2020, 4)

日付オブジェクトからインスタンス作成

from datetime import date

ym.parse(date.today())  #=> ym(2020, 7)
from datetime import datetime

dt = dateime.now()
ym.parse(dt.date())  #=> ym(2020, 7)

年, 月 を取得

current = ym.current()  #=> ym(2020, 7)
current.y  #=> 2020
current.m  #=> 7

加算, 減算

ym(2020, 4) + 10  #=> ym(2021, 2)
ym(2020, 4) - 10  #=> ym(2019, 6)

年月の差

ym(2020, 7) - ym(2020, 4)  #=> 3

比較演算

ym(2020, 7) < ym(2020, 4)  #=> False
ym(2020, 7) > ym(2020, 4)  #=> True
ym(2020, 7) == ym(2020, 4)  #=> False

範囲取得

list(ym(2020, 4).to(2020, 7))  #=> [ym(2020, 4), ym(2020, 5), ym(2020, 6)]
current = ym.current()  #=> ym(2020, 7)
list(current.to(current + 6))  #=> [ym(2020, 7), ym(2020, 8), ym(2020, 9), ym(2020, 10), ym(2020, 11), ym(2020, 12)]
2
6
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
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?