Stan
Stan

Reputation: 884

Issues in getting week numbers with weeks starting on Sunday in Python?

I am using Python 3.6 and having issues getting week numbers starting from Sunday.

How can I find week numbers with weeks starting on Sunday in Python?

t1 = datetime.datetime.now()

t1.strftime("%U")

For example, on 09/16/2018 Sunday it should give WW38 and not WW37, which it is giving now.

I see that both "%U", "%V" and "%W" are giving the same.

Any help will be appreciated.

A small cut of the dataframe is as below:

   time                   value
2018/09/15 1:08:19 PM   11.87
2018/09/16 6:23:17 PM   10.794
2018/09/16 6:37:48 PM   10.313
2018/09/16 6:54:14 PM   10.578
2018/09/16 6:58:24 PM   11.057
2018/09/19 9:08:24 PM   13.09

For each of the time I am creating a WW column.. The issue is that I want the WW to start on Sunday and not Monday.

My code:

ww_l =[]
for date in df['time']:  
  date_v = datetime.strptime(tv, "%Y-%m-%d %H:%M:%S")  
  curr_ww = datetime.date(date_v).strftime("%W")   
  ww_l.append(curr_ww)
df['WW'] = pd.DataFrame(ww_l)

Upvotes: 5

Views: 3806

Answers (2)

Kamran Syed
Kamran Syed

Reputation: 459

You can set first day of week (which you want to set as Sunday) as below:

import calendar
calendar.setfirstweekday(calendar.SUNDAY)

Documentation can be found here

Upvotes: 0

Ben.T
Ben.T

Reputation: 29635

A work around could be to add a day at df['time'] and then get the week. Like this, if you are at Sunday, then add a day bring to Monday and getting the week of the Monday would be the one you look for, and for the other days it does not change anything, such as:

df['WW'] = (df['time'] + pd.Timedelta(days=1)).dt.week

EDIT: thanks to @pygo, you can use pd.Dateoffset to add a day instead of pd.Timedelta such as:

df['WW'] = (df['time'] + pd.DateOffset(days=1)).dt.week

And you get like expected:

print (df)
                 time   value  WW
0 2018-09-15 13:08:19  11.870  37
1 2018-09-16 18:23:17  10.794  38
2 2018-09-16 18:37:48  10.313  38
3 2018-09-16 18:54:14  10.578  38
4 2018-09-16 18:58:24  11.057  38
5 2018-09-19 21:08:24  13.090  38

Upvotes: 4

Related Questions