Shantanu
Shantanu

Reputation: 867

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

Upvotes: 3

Views: 5261

Answers (2)

Primusa
Primusa

Reputation: 13498

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.

Upvotes: 2

Andrei
Andrei

Reputation: 1373

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

Upvotes: 4

Related Questions