I had to work with Nagios a lot this morning, in particular reading through the nagios.log
log file. If you're ever read that log file, or looked at some other Linux/Unix log files, you've seen records that display the time in an epoch time format, which looks like this:
1219822177
If you can read the epoch time format and know the actual human readable date and time, you're a better person than I am (or you've been looking at Nagios, Linux, or Unix log files too long).
To help me read these date/time records I created a simple Perl date-conversion program I named epochtime.pl
. In short, you run the program like this:
epochtime.pl 1219822177
and it produces output like this:
2008/08/27 03:29:37
(Maybe a computer can't read that time format very well, but a human can read it pretty easily.)
My epoch time converting Perl script
Given that introduction, here is the source code for my epochtime.pl
Perl script:
#!/usr/bin/perl # ------------------------------------------------------------ # epochtime.pl # ------------ # from devdaily.com # a perl script to convert Nagios "epoch time" (epoch seconds) # into a human-readable format. # ------------------------------------------------------------ $num_args = $#ARGV + 1; die "Usage: this-program epochtime (something like '1219822177')" if ($num_args != 1); $epoch_time = $ARGV[0]; ($sec,$min,$hour,$day,$month,$year) = localtime($epoch_time); # correct the date and month for humans $year = 1900 + $year; $month++; printf "%02d/%02d/%02d %02d:%02d:%02d\n", $year, $month, $day, $hour, $min, $sec;
Discussion
If you're an experienced Perl programmer this script isn't too hard to decipher. Here's an explanation of how it works:
- I use the special Perl
$#ARGV
variable to determine how many command line arguments there are. - Since there must be only one command line argument, the next thing I do is
die
if the number of arguments does not equal 1. - To make the program a little easier to understand I create the variable
$epoch_time
. - I use the
localtime
method to convert the epoch time into six separate variables. - I make adjust the
$year
and$month
to again make them more human readable. - I use
printf
to print the output in a nice format.
This Perl program is free for you to use (open source), so customize it, change the date and time format, etc.