[Python] Obtaining American-style week numbers

Purpose of this article

When I was trying to get the week number, Since the following phenomena were confirmed, the cause and countermeasure memo

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

> (2016, 52, 7)

Why is New Year's Day 2017 2016! ??

Cause

According to the following article, Calculate week numbers in Python

ISO 8601 week number definition The week including the first Thursday is the first week. The week starts on Monday. American week number definition The week including January 1st is the first week. The week starts on Sunday.

That means. In other words, the above result seems to be correct in the format of ISO8601. But this time I want the result of `American` ...

Countermeasures

I searched and found no way to change isocalendar () `` `to American `` `, so I wrote the code myself.

2020/03/27 postscript: The code was incorrect, so I fixed it.

def american_calendar(year, month, day):
    #Datetime of input year.Create date type data
    inp = datetime.date(year=year, month=month, day=day)
    #Datetime on New Year's Day of input year.Create date type data
    first = datetime.date(year=year, month=1, day=1)

    #First,Calculation of the day of the week
    inp_how = (inp.weekday()+1) % 7 #+1 is to change the day of the week to start on Sunday
    first_how = (first.weekday()+1) % 7
    
    #Less than,Week number calculation
    #Upper left of the calendar(First sunday)Get the date
    upper_left = first - datetime.timedelta(days=first_how)

    #Get the week number by calculating the difference in the number of days from the base date
    inp_week = (inp - upper_left).days // 7
    
    return year, inp_week, inp_how

When you check the operation

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

> (2017, 0, 0)

It now returns the value you want.

that's all!

reference

Note other than the work of a certain engineer: Calculate week number with Python Python documentation: date.isocalendar ()

Recommended Posts

[Python] Obtaining American-style week numbers
Memorize Python commentary 3 --Numbers
Prime numbers in Python
Determine prime numbers with python
Python OCR recognizes single-letter numbers
Separate numbers by 3 digits (python)
Handle complex numbers in Python
Playing handwritten numbers with python Part 1
Testing with random numbers in Python
[python] week1-3: Number type and operation
[Python] Convert natural numbers to ordinal numbers
Convert decimal numbers to n-ary numbers [python]
Law of large numbers in python
[Python] nCr mod Compute prime numbers
[Python] Change the alphabet to numbers