user2458008
user2458008

Reputation: 51

Need Sunday as the first day of the week

I would like Sunday to be 0, but when using the datetime weeday methods it's 6:

datetime(2013, 6, 9, 11, 59, 59, 1).weekday()  # this returns 6

My locale is: "en_US.UTF-8" so Sunday should be 0 (when I run 'locale day' at bash prompt, it correctly shows 'Sunday' as first day of the week).

$ locale day
Sunday;Monday;Tuesday;Wednesday;Thursday;Friday;Saturday

How can I get python to show Sunday as the first day of the week?

(I'm using a pandas timeseries and calling .date to get the datetimes.)

Upvotes: 5

Views: 8943

Answers (2)

Gauthier Boaglio
Gauthier Boaglio

Reputation: 10262

Try this :

(datetime.datetime(2013, 6, 9, 11, 59, 59, 1).weekday() + 1) % 7

Upvotes: 16

Andy Hayden
Andy Hayden

Reputation: 375865

Rather than going via date (creating datetime objects) use the dayofweek attribute (which will be faster):

In [1]: rng = pd.date_range('1/1/2013', periods=72, freq='D')

In [2]: (rng.dayofweek + 1 ) % 7
Out[2]:
array([2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3,
       4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5,
       6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0,
       1, 2, 3], dtype=int32)

You could make this an attribute:

In [3]: rng.my_dayofweek = (rng.dayofweek + 1 ) % 7

Similarly you could calculate your own week:

In [4]: rng.my_week = rng.map(lambda x: x.week if x.dayofweek else x.week - 1)

Which would then be available to you as attributes.

.

The datetime.date weekday method is not locale specific, it's hardcoded (here's its docstring):

Return the day of the week represented by the date.
Monday == 0 ... Sunday == 6

Upvotes: 2

Related Questions