Search code examples
pythondatetimestrftime

python - Year-week combination for the end or beginning of a year


I want to construct YYYY_WW information from dates (where WW is a number of week). I am struggling with the years' endings (beginnings), where a part of a week can fall into the neighbouring year:

import datetime
import pandas as pd

# generate range of dates and extract YYYY_WW
dates_range = pd.date_range(start='2018-12-29', end='2019-01-02')
weeks = dates_range.strftime("%Y_%V")
print(weeks)

#Index(['2018_52', '2018_52', '2018_01', '2019_01', '2019_01'], dtype='object')

2018_01 is obviously incorrect. Any hint for a simple workaround?


Solution

  • You are looking for the %G directive:

    ISO 8601 year with century representing the year that contains the greater part of the ISO week (%V).

    See strftime() and strptime() behavior for details.

    For example:

    import datetime
    import pandas as pd
    
    dates_range = pd.date_range(start='2018-12-29', end='2019-1-2')
    weeks = dates_range.strftime('%G_%V')
    print(weeks)
    # Index(['2018_52', '2018_52', '2019_01', '2019_01', '2019_01'], dtype='object')