A simple Python example

Ever wanted a calendar that displays dates in hexadecimal? Probably not, but here is one anyway...

The calendar module has a function called monthcalendar that returns the calendar for a certain month and year, as a matrix with each row representing a week of seven days. Days outside the month are represented by zeroes.

We can get the information interactively from Python for June 2000:

[~/work/python_talk/]> python
Python 1.5.2 (#1, Feb  1 2000, 16:32:16)  [GCC egcs-2.91.66 19990314/Linux
(egcs- on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import calendar
>>> print calendar.monthcalendar(2000, 6)
[[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17,
18], [19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 29, 30, 0, 0]]
>>> 

The following is a script that allows the user to enter the month and the year (with error checking) producing a nicely formatted calendar, in hex:

#!/usr/bin/env python
# -*- python -*-
#
#      Name: hexcal
#   Purpose: Displays a calendar in hex
#
#    Author: Graeme Cross <gcross@netspace.net.au>
# Copyright: Graeme Cross
#   Created: 26 June 2000
#       RCS: $Id: simple.html,v 1.1 2000/07/09 23:18:40 mib Exp $
#

# import the modules we are going to use
import sys
from calendar import *

# make sure we have the right number of command line parameters
if len(sys.argv) != 3:
    print "\nSyntax: hexcal month year (where month is 1 - 12)\n"
    sys.exit(1)
	
# convert the two command line parameters to numerical values
# (they come in as strings)
try:
    month = int(sys.argv[1])
    year  = int(sys.argv[2])

    # get the matrix of days and weeks in the month
    monthMatrix = monthcalendar(year, month)

except ValueError, message:
    print "Error:", message
    sys.exit(2)

# print out the heading
print "%s %d\n" % (month_name[month], year)

# print out each day in hex; if the day = 0, then leave it blank
for week in monthMatrix:
    for day in week:
        if day == 0:
	    print "  ",
	else:
	    print "%2s" % (hex(day)[2:]), 
    print

# eof

Running it (./hexcal.py 6 2000) produces:

	June 2000

	          1  2  3  4
	 5  6  7  8  9  a  b
	 c  d  e  f 10 11 12
	13 14 15 16 17 18 19
	1a 1b 1c 1d 1e      

Note: you need to have the +x flag set on the script to run it like this. The other way of running the script is: python hexcal.py 6 2000


[Previous] [Next]