Skip to content

Instantly share code, notes, and snippets.

@atr000
Created April 6, 2010 20:02
Show Gist options
  • Save atr000/358025 to your computer and use it in GitHub Desktop.
Save atr000/358025 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# author: Martin Michel
# created: 29.03.2010
# The script prints all dates of the given year together with the
# corresponding week and weekday number
# Useful when you need to know the dates of a week number
import calendar
import time
from optparse import OptionParser
def main():
# parsing the given command line arguments
parser = OptionParser(usage = "usage: %prog [options]", version = "%prog 1.0")
parser.add_option("-y", "--year",
type="int",
dest="year",
help="the year you want to process")
parser.add_option("-f", "--firstweekday",
type="int",
dest="firstweekday",
help="first day of the week: 0 is Monday, 6 is Sunday")
parser.add_option("-w", "--weekmode",
type="string",
dest="weekmode",
help="week number mode: U or W (ISO)")
parser.add_option("-d", "--weekday",
type="int",
dest="weekday",
help="week day mode: 1 (Monday = 1, Sunday = 7) or 2 (Monday = 0, Sunday = 6)")
(options, args) = parser.parse_args()
# did the user provide all and valid arguments?
if len(args) != 0:
parser.error("Wrong number of arguments")
if options.year is None:
parser.error("Missing year argument (-y)")
if options.firstweekday is None:
parser.error("Missing firstweekday argument (-f)")
else:
if not options.firstweekday in (0, 1, 2, 3, 4, 5, 6):
parser.error("the firstday argument must be a number from 0 to 6 (not %i)" % options.firstweekday)
if options.weekmode is None:
parser.error("Missing weekmode argument (-w)")
else:
if not options.weekmode in ('U', 'W'):
parser.error("the weekmode argument must be 'U' or 'W' (not %s)" % options.weekmode)
if options.weekday is None:
parser.error("Missing weekday argument (-d)")
else:
if not options.weekday in (1, 2):
parser.error("the weekmode argument must be 1 or 2 (not %i)" % options.weekday)
# finally we generate the output :D
weekmode = '%' + options.weekmode
cal = calendar.Calendar(options.firstweekday)
for monthnum in range(1, 13):
for date in cal.itermonthdates(options.year, monthnum):
# only process this year, not the previous or next
if date.year != options.year:
continue
weeknumstr = date.strftime(weekmode)
datestr = date.strftime('%d.%m.%Y')
if options.weekday == 1:
weekdaynum = date.isoweekday()
else:
weekdaynum = date.weekday()
print "%s\t%s\t%i" % (weeknumstr, datestr, weekdaynum)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment