Script - get calendar week number (but start with Monday not Sunday)

Hello,
i need some hint about system.date.format.
I need to format date to string like: “dd. MM. YYYY/w”
That w is calendar week. But when I use this function I get Calendar weeks starting by Sunday (so if the date is hits Sunday, KW number is wrong for me).

a) Do you know any elegant way how get KW starting by Monday (some settings or elegant code).
b) There is option to use ifs and add +1 if this is Sunday (but this is plan B for me).

Thank you

Since system.date.format uses the java SimpleDateFormat and SimpleDateFormat uses the Locale to determine which day is the start of the week, I assume that this is based on the project’s locale?

Perhaps @PGriffith or @cmallonee can speak more to this?

Java’s Calendar class allows you to set the first day of the week (docs). If you’re comfortable importing classes from Java this would be the easiest way.

2 Likes

Look at the strftime method from date time.

import datetime
today = datetime.date.today()
year, week, day = today.isocalendar()

# adjust for the week starting at 0
weekStartSun = int(today.strftime("%U")) + 1
weekStartMon = int(today.strftime("%W")) + 1

print year, week, weekStartSun, weekStartMon

2 Likes

Thank you,
i reused your example.
M.

Method strftime("%W") is not working corectly. weekStartMon = 53 for date 18th December 2024. Correct value should be 52 according to ISO (see Wikipedia).
Use just isocalenda() method to get week number starting on Monday according to ISO/European standard. Week number 1 is week containing first Thursday in January.

import datetime
today = datetime.date.today()			# get actual date 
today = datetime.date(2024,12,18)		# set date manualy
print today,type(today)

year, week, day = today.isocalendar()

print "ISO calendar year = ",year
print "ISO calendar week = ",week
print "ISO calendar day (1..7 = Mo..Su) = ",day