Home > Software design >  How can I have the exact date for a certain week of the year?
How can I have the exact date for a certain week of the year?

Time:10-08

I have the following data:

week = [202001, 202002, 202003, ..., 202052]

Where the composition of the variable is [year - 4 digits] [week - 2 digits] (so, the first row means it's the first week of 2020, and so on).

I want to transform this, to a date-time variable [YYYY - MM - DD]. I'm not sure what day could fit in this format :( maybe the first saturday of every week.

week_date = [2020-01-04, 2020-01-11, 2020-01-18, ...]

It seems like a simple sequence, neverthless I have some missings values on the data, so my n < number of weeks of 2020.

The main purpose of this conversion is that I can have a fit model to train in prophet. I also think I need no missing values when incorporating the data into prophet, so maybe the answer could be also adding 0 to my time series?

Any ideas? Thanks

CodePudding user response:

Try:

l =  [202001, 202002, 202003, 202052]

out [datetime.datetime.fromisocalendar(int(x[:4]), int(x[4:]), 6).strftime("%Y-%m-%d") for x in map(str,l)]
print(out)

outputs:

['2020-01-04', '2020-01-11', '2020-01-18', '2020-12-26']

Here I used 6 as the week day but chose as you want

This makes a datetime object from the first and last part of each number after mapping them to a string, then outputs a string back with strftime and the right format.

CodePudding user response:

Thank you so much to everyone. The other question help me so much Pandas: How to create a datetime object from Week and Year?. Love this platform

  • Related