LoginSignup
1
0

Pythonで1ヶ月前を求める時

Posted at

標記でネットを調べると、みんなdateutil を使うってなっているけど、わざわざutility使うことないのではと思って、下の関数を作成しました

これは、YYYYMMのフォーマットで文字列6桁の年月を受け取り、1ヶ月前を返すものです

今の所、問題ない感じですね

get_pre_month.py
def get_pre_month(year_month: str) -> str:
    y = int(year_month[0:4])
    m = int(year_month[4:6])

    if m == 1:
        y -= 1
        return f"{y}12"

    m -= 1
    # 0 padding
    return f"{y}{m:02}"
test_app.py
def test_get_pre_month():
    assert app.get_pre_month("202403") == "202402" 
    assert app.get_pre_month("202401") == "202312"
    assert app.get_pre_month("202312") == "202311"
1
0
1

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
1
0