Monday, December 15, 2008

Find the Last Day of the Previous Month

If you need to generate monthly report for the previous month and you want to get cron to help you to automate the scheduling, you will need this script to determine exactly how many days in the previous month. For example, in sar (system activity report), by default the data are kept only for a month and they will be overwritten. Suppose you need to dump out the CPU utilisation for the entire previous month, you will need to schedule cron to run on the 1st day of the month to find out all the SAR files using
find /var/adm/sa -type f -mtime -30 -name "sa*"
if previous month has 30 days.

Here is short Python script that can do the job:

$ date
Mon Dec 15 21:00:08 MPST 2008

$ cat lastmth.py
#! /usr/bin/python

import datetime, time

mth_this_now   = datetime.date.today()
mth_this_start = datetime.date(mth_this_now.year, mth_this_now.month, 1)
mth_last_end   = mth_this_start - datetime.timedelta(days=1)
print mth_last_end.year, mth_last_end.month, mth_last_end.day

$ ./lastmth.py
2008 11 30

Labels: ,

0 Comments:

Post a Comment

<< Home