LoginSignup
3
3

More than 3 years have passed since last update.

【Python】アメリカ式の週番号の取得

Last updated at Posted at 2020-03-25

この記事の目的

週番号を取得しようとしていたときに,
以下のような現象を確認したので, 原因と対策メモ

import datetime
datetime.date(year=2017, month=1, day=1).isocalendar()

> (2016, 52, 7)

なんで2017年の元日が2016年なの!?

原因

次の記事によると, Pythonで週番号を計算する

ISO8601の週番号の定義
最初の木曜日を含む週を第1週とする. 週の始まりは月曜日.
アメリカ式の週番号の定義
1月1日を含む週を第1週とする. 週の始まりは日曜日.

ということ.
つまりISO8601の形式だと, 上の結果で正しいみたい.
しかし, 今回はアメリカ式の結果が欲しい...

対策

調べても, isocalendar()アメリカ式に変更する方法などは見つからなかったので, 自分でコードを書きました.

2020/03/27追記:コードが間違っていたので修正しました.

def american_calendar(year, month, day):
    #入力年のdatetime.date型データを作成
    inp = datetime.date(year=year, month=month, day=day)
    #入力年の元日のdatetime.date型データを作成
    first = datetime.date(year=year, month=1, day=1)

    #まず, 曜日の計算
    inp_how = (inp.weekday()+1) % 7 #+1は曜日を日曜始まりに変更するため
    first_how = (first.weekday()+1) % 7

    #以下, 週番号の計算
    #カレンダーの左上(最初の日曜日)の日付を取得
    upper_left = first - datetime.timedelta(days=first_how)

    #基準日との日数差を計算して週番号を取得
    inp_week = (inp - upper_left).days // 7

    return year, inp_week, inp_how

動作を確認すると

american_calendar(year=2017, month=1, day=1)

> (2017, 0, 0)

希望通りの値を返してくれるようになりました.

以上!

参考

某エンジニアのお仕事以外のメモ:Pythonで週番号を計算する
Pythonドキュメント:date.isocalendar()

3
3
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
3
3