python - 年末或年初的年周组合

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

我想根据日期(其中 WW 是周数)构建 YYYY_WW 信息。我正在为这些年的结束(开始)而苦苦挣扎,其中一周的一部分可能会落入下一年:

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 显然是不正确的。任何简单解决方法的提示?

您正在寻找 %G 指令:

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

详情见strftime() and strptime() behavior

例如:

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')