Skip to content
Advertisement

How to retrieve the week number of the year starting at 1 Jan?

So I have a shell script which returns me the week number using an SQL query :

JavaScript

This query returns 1. (Starting at 1st Jan)

Python code: I have tried the following however it returns 52 rather than 1 :

JavaScript

Week starting from Mon-Sun

Is there another way in which I can get the week number of year based on starting at 1st Jan so I get 1 for 01/01/2022?

Required output:

JavaScript

Advertisement

Answer

Is there another way in which I can get the week number of year based on starting at 1st Jan so I get 1 for 01/01/2022?

You can use, for a given date dt, as you said in the question:

JavaScript

or can calculate it using:

JavaScript

or, to match the python code, can get the ISO week using:

JavaScript

Or, if you want to start counting the week from the 1st January and change weeks on a Monday then:

JavaScript

Then the query:

JavaScript

Outputs:

DT WEEK ISOWEEK WEEKFROMYEARSTART MONTOSUNWEEKFROMYEARSTART
2021-12-30 52 52 52 53
2021-12-31 53 52 53 53
2022-01-01 1 52 1 1
2022-01-02 1 52 1 1
2022-01-03 1 1 1 2
2022-01-04 1 1 1 2
2022-01-05 1 1 1 2
2022-01-06 1 1 1 2
2022-01-07 1 1 1 2
2022-01-08 2 1 2 2
2022-01-09 2 1 2 2
2022-01-10 2 2 2 3
2022-01-11 2 2 2 3
2022-01-12 2 2 2 3
2022-01-13 2 2 2 3
2022-01-14 2 2 2 3
2022-01-15 3 2 3 3
2022-01-16 3 2 3 3
2022-01-17 3 3 3 4
2022-01-18 3 3 3 4
2022-01-19 3 3 3 4
2022-01-20 3 3 3 4
2022-01-21 3 3 3 4
2022-01-22 4 3 4 4
2022-01-23 4 3 4 4
2022-01-24 4 4 4 5
2022-01-25 4 4 4 5
2022-01-26 4 4 4 5
2022-01-27 4 4 4 5
2022-01-28 4 4 4 5
2022-01-29 5 4 5 5
2022-01-30 5 4 5 5
2022-01-31 5 5 5 6
2022-02-01 5 5 5 6
2022-02-02 5 5 5 6
2022-02-03 5 5 5 6
2022-02-04 5 5 5 6
2022-02-05 6 5 6 6
2022-02-06 6 5 6 6
2022-02-07 6 6 6 7

db<>fiddle here


If you want a Python function then:

JavaScript

or:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement