Perl Tricks – timestamps
Running perl integration tools we have two basic needs for time stamps and date time values.
First, it is useful to note the time that something is happening in a log file so that we don’t have to guess.
Second, it is also useful to append the date to a file name to keep our logs in daily files not just one long never ending file.
Here is a function that I use to do both of these things.
sub timestamp($)
{
#return pre-formatted timestamps based on the localtime()
#”date” asks for a Month-Day-Year string.
#”date” time asks for the date and time.
#anything else returns the epoch date.
my $param = $_[0];
if ($param eq “date”)
{
@time = split(/ /, localtime());
$return = $time[1] . “-” . $time[2] . “-” . $time[4];
return $return;
}
elsif ($param eq “datetime”)
{
return localtime();
}
else
{
return time();
}
}
How to use
When we call this function within a perl script we will want one of three things back.
1. If we want the date or DATESTAMP, we will call it in this manner,
timestamp(date)
and it will return the formatted date that we have formatted like this, “Mar-29-2010″
This call can be withing a string like a file name $filename = “Log” . timestamp(date) . “.log”; or just set as a variable, $date = timestamp(date);
2. If we want the date and time or TIMESTAMP, we will call it in this manner,
timestamp(datetime)
and it will return a formatted string like this, “Thu Apr 15 17:01:10 2010″
This can be called the same way. However, don’t use this in a file name. It contains spaces. And having a unique file every second might not be useful to you.
3. If we just want the epoc date back, we just call it in this maner,
timestamp()
but why bother. I wanted the function to return something all the time so that you can tell when you have the parameter flag misspelled, but you could just you time() for that.
In any case this is a function that I like to use when I am creating timestamps for my log files. It is easily extended by adding new elsif conditions and handling the localtime() or time() with a different split or regular expression.
Subscribe to "The Integration Engineer" by Email
Find out about the tools and services available at The Integration Engineer's Consulting site.

