Convert Date to CalendarWeek

For whoever wants to calculate/transfer a Date or DateTime into a calendar week value,
i.e. 2017/09/04 = calendar week 36

I got a few python lines from stackoverflow and used them with “DateTime.Format”

The python code:
import clr
clr.AddReference(‘ProtoGeometry’)
from Autodesk.DesignScript.Geometry import *
dataEnteringNode = IN
from datetime import datetime, date, time
AnalysisDate = str(IN)
AnalysisDateShort = AnalysisDate [2:-2]
dt = datetime.strptime(AnalysisDateShort, ‘%Y-%m-%d’)
d = dt.date()
year, week, weekday = d.isocalendar()
OUT = week

2 Likes

This one’s a bit shorter:

import clr
import datetime
year = IN[0]
month = IN[1]
day = IN[2]
OUT = datetime.date(year, month, day).isocalendar()[1]

grafik

4 Likes

it might not be as accurate but it’s short and simple :slight_smile:

2 Likes

Our first working day of the week is sunday. Using the solutions above gave the following : if I convert 15/12/2009 to week number the conversion week is 51 which is OK. If I convert 13/12/2009 (Sunday) to week number the result is week No. 50 which does not confirm with our working calendar.
How to set Sunday as the first day of the week so that the conversion will confirm with our working calender?
Thanks

Isocalendar is for the ISO date standard which is a pretty specific thing. You could take the code above and replace the bottom output line with

OUT = datetime.date(year, month, day).strftime("%U")

Which will give you the week starting Sunday.

The other thing you’ll run into is if your standards for what ‘week 1’ is differ. If Jan 1st is a Tuesday is that week 1, or do you need to wait for a Monday? If that Tuesday is week 1 by your standards, then what if Jan 1st is a Friday, is that still week 1? The ISO date has a standard for this but yours might differ, and I’m not sure how the strftime functions determine it.