sdispater / pendulum

Python datetimes made easy
https://pendulum.eustace.io
MIT License
6.2k stars 383 forks source link

Week of Year is Incorrect #500

Open curious247 opened 4 years ago

curious247 commented 4 years ago

dt = pendulum.parse('2019-01-01') print(dt.week_of_year)

1

dt = pendulum.parse('2019-12-31') print(dt.week_of_year)

1

dt = pendulum.parse('2020-01-01') print(dt.week_of_year)

1

An option is to include 53 as 'week_of_year' for '2019-12-31'.

Also, '2019-01-01' and '2020-01-01' have the same problem. To clarify, the first Sunday in 2020 is on 2020-01-04. An option is to set 'week_of_year' as 0 or -1 for 'week_of_year' for dates that come before the first Sunday of the year.

pmav99 commented 3 years ago

I believe that pendulum is following the ISO definition of weekdays, i.e. it is behaving similar to date.isocalendar() in the standard library: https://docs.python.org/3/library/datetime.html#datetime.date.isocalendar

if this assumption is correct, then pendulum is doing the right thing.

curious247 commented 3 years ago

Yes, the issue with this approach is that '2019-01-01' and '2019-12-31' have the same week number of 1 even though they are in the same year. To me, this is ripe for leading to errors in date calculations based on the week of the year unless the month of the year is also taken into account.

In other words, it is not an elegant approach.

gs202 commented 3 years ago

There is also an issue with 2021 pendulum.now('UTC') # DateTime(2021, 1, 3, 7, 54, 38, 285672, tzinfo=Timezone('UTC') pendulum.now('UTC').week_of_year # 53

Should be week 1 of 2021

pmav99 commented 3 years ago

@gs202 I think it should be week 53:

The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.

gs202 commented 3 years ago

@gs202 I think it should be week 53:

The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.

I guess you are right. When using isocalendar i am getting the correct expected result But had a bug in my code where i used pendulum.now('UTC').week_of_year to get the week and pendulum.now('UTC').year to get the year - got it messed up