# List of first work days of month for any year

To be more clear, I post this 'unnecessary optimization' of Vegaseat's code in new thread instead of end of old one. Just to show that this is even simpler than checking if given day is first weekday of the month.

1,209 Views

IT Pro doing Eng-Fin-Eng translations

``````"""Task: calculate this list (from vegaseat

All first workdays of each month in 2011:
1) Mo  01/03/2011
2) Tu  02/01/2011
3) Tu  03/01/2011
4) Fr  04/01/2011
5) Mo  05/02/2011
6) We  06/01/2011
7) Fr  07/01/2011
8) Mo  08/01/2011
9) Th  09/01/2011
10) Mo  10/03/2011
11) Tu  11/01/2011
12) Th  12/01/2011

"""

from datetime import date, timedelta

def first_workday(month, year):
first = date(year, month, 1)
if first.weekday() < 5:
return first
return first + timedelta(days=7-first.weekday())

year = 2011
for month in range(1,13):
print(' %2i) %s' % (month, first_workday(month,year).strftime('%a %m/%d/%Y')))

# Produces three letter weekday name instead of two letters``````
TrustyTony 888

Not only way to do it of course (in spite of Python philosophy):

``````"""Task: calculate the list from vegaseat
"""

from datetime import date, timedelta

def first_workday(month, year):
first = date(year, month, 1)
return first if first.weekday() < 5 else first.replace(day=8 - first.weekday())

def table(year = 2011):
print('\n'.join(' %2i) %s' %
(month, first_workday(month,year).strftime('%a %m/%d/%Y'))
for month in range(1,13)))
# Produces three letter weekday name instead of two letters

table()``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.