Home > bash > Printing days of the month.

Printing days of the month.

I needed to have the dates of the month for reporting purposes. As time was not on my side, I had my collegue do this for me in python. Later on I managed to do this in bash. (NB: The sample code below does not give the exact same results.)

Here is the bash version.

#!/bin/bash
#=============================================================================
#
# FILE: create_dates.sh
#
# USAGE: create_dates.sh [MONTH] [YEAR]
#
# DESCRIPTION: Lists the days of the given month for the given year in the
#              following format yyyy-mm-dd. If either value is not specified
#              then the current MONTH and/or YEAR is used.
#
#=============================================================================

month="$1"
year="$2"

#=== FUNCTION ================================================================
#           NAME: usage
#    DESCRIPTION: Display usage information for this script.
#    PARAMETER 1: ---
#=============================================================================
function usage()
{
cat <<- EOT
Lists the days of a given month in yyyy-mm-dd format.

usage: $0 [MONTH] [YEAR] [--help]

Optional values
    MONTH -- the month to use
    YEAR -- the year to use
    help -- display this message
EOT
}

#-----------------------------------------------------------------------------
# Display usage
#-----------------------------------------------------------------------------
if [ "$1" == "--help" ]
then
    usage
    exit
fi

#-----------------------------------------------------------------------------
# Assign default values if needed.
#-----------------------------------------------------------------------------
if [ -z "$month" ]
then
    month=$(date "+%m")
fi

if [ -z "$year" ]
then
    year=$(date "+%Y")
fi

#-----------------------------------------------------------------------------
# main
#-----------------------------------------------------------------------------
for day in $(cal $month $year);
do  echo $day  | \
    sed -n -e "s/^[0-9]$/${year}-${month}-0&/" \
           -e "s/^[0-9][0-9]$/${year}-${month}-&/" \
           -e "/^${year}-/p" | sed "s/.*/&,0/"
done

And here is the verbose python version.

#!/usr/bin/python
"""Create a file containing the days in a given month, for a given year.

For a given month, create a two column csv file, the first column holds the
days in the month. The date format is YYYY-MM-DD. The second column holds data
values, they are all set to zero.

The following should be specified.
 year            The desired year.
 month           The desired month.
 output_file     The file to write the dates to.

Options:
 --help          Print this message and exit.

"""
import calendar
import sys
import getopt

USAGE_TEXT = """Usage: create_date_file.py year month output_file
For more verbose descriptions, use create_date_file.py --help """

def help():
 print >> sys.stderr, __doc__
 sys.exit(0)

def usage(code, msg=''):
 """Print usage or error.

 Keyword arguments:
 code -- The exit status code.
 msg -- The message to print out.

 """
 print >> sys.stderr, msg
 sys.exit(code)

def create_date_file(file, month, year):
 """Create date file.

 Keyword arguments:
 file -- The name of the file to write to.
 month -- The desired month.
 year -- The desired year.

 """
 # Get the last day of the month
 last_day = calendar.monthrange(year, month)[1]

 temp_file = open(file, 'wb')
 for day in range(1, last_day + 1):
 temp_file.write(str(year) + "-" + str(month).zfill(2) + "-" +
 str(day).zfill(2) +",0 \n")
 temp_file.close()

def main():
 try:
 opts, args = getopt.getopt(sys.argv[1:], '',
 ['help'])

 for opt, arg in opts:
 if opt in ('--help'):
 help()

 year = int(args[0])
 month = int(args[1])
 file = args[2]
 create_date_file(file, month, year)

 except getopt.error, msg:
 usage(1, msg)
 except IndexError:
 usage(1, USAGE_TEXT)
 except ValueError:
 usage(1, USAGE_TEXT)

if __name__ == '__main__':
 main()

 

 

Advertisements
Categories: bash Tags: ,
  1. No comments yet.
  1. February 17, 2016 at 6:37 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s