Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to get the current week number (not ISO)

I'm looking for an easy way to get the current week number of the year in Python. I'm well aware of the datetime.datetime.isocalendar() function in the standard library, but this function stipulates that week 1 is the first Monday of the new year. My dilemma is that I'm using Sunday as a starting point for each week, and if Sunday is for example December 27 and January 1st appears at some point during that week, I need to represent that week as week 1 (and year 2015).

I thought of doing something like (pseudocode):

if (Jan 1) - (current_sunday) < 7 days:
    week_num = 1

And then storing that week number somewhere to iterate over next week. However, I feel that this is a very hackish method and would prefer something cleaner.

like image 636
Jon Martin Avatar asked Sep 03 '25 06:09

Jon Martin


1 Answers

Generally to get the current week number (starts from Sunday):

>>> import datetime
>>> import calendar
>>> today = datetime.date.today())
>>> (int(today.strftime('%U')) + (datetime.date(today.year+1, 1, 1).weekday() != calendar.SUNDAY)) % 53
12

From the documentation of strftime('%U'):

"Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0."

Hence the modified code for your specific requirements. There isn't really a non-hacky way to do what you want.

like image 120
anon582847382 Avatar answered Sep 04 '25 19:09

anon582847382