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

1

5

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?

Simile answered 11/3, 2019 at 17:4 Comment(2)
What behavior do you want? ISO definition, meaning 2018-12-31 is in week 1 of 2019?Emrich
I need ['2018_52', '2018_52', '2019_01', '2019_01', '2019_01'], which should be in line with ISO, see e.g. hereSimile
H
6

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')
Holbrooke answered 11/3, 2019 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.