Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Year-Week format in ISO calendar format?

I am trying to get the current date in ISO Calendar format as follows alongwith the zero padding on the week?

2019/W06

I tried the following, but prefer something using strftime as it is much easier to read.

print(str(datetime.datetime.today().isocalendar()[0]) + '/W' + str(datetime.datetime.today().isocalendar()[1]))
2019/W6
like image 436
Shantanu Avatar asked Nov 17 '25 04:11

Shantanu


2 Answers

Use following code:

print(datetime.now().strftime('%Y/W%V'))

%Y Year with century as a decimal number.

%V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week.

https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior

like image 56
Andrei Avatar answered Nov 19 '25 19:11

Andrei


Solution with strftime:

If you want the zero padding:

datetime.date.today().strftime("%Y/W%V")

Output:

2019/W06

If you don't want it:

datetime.date.today().strftime("%Y/W%-V")

Output:

2019/W6

Note that "%V" returns the week number, and the "-" is what removes the leading zero.

like image 35
Primusa Avatar answered Nov 19 '25 18:11

Primusa