When I do something like this I usually just use the date command. Perhaps if I run a command that takes a while and I want to see about how long it ran I run something like...
(date && COMMAND && date) > output.txt
Then when I look in the output file, it will show the date before the command starts, and after the command finishes. In Perl the code would look something like this...
$ perl -e '$cmd=q(date && echo "sleeping 3 seconds" && sleep 3 && date); print for(`$cmd`);'
Thu Aug 21 02:54:45 AM CDT 2025
sleeping 3 seconds
Thu Aug 21 02:54:48 AM CDT 2025
So if you wanted to print out the time in a logfile you could do something like this...
#!/usr/bin/perl -w
open(my $fh, ">", "logfile.txt");
my ($dateCommand, $sleepCommand, $date, $sleep);
$dateCommand = "date";
$sleepCommand = "sleep 3";
chomp($date =`$dateCommand`);
print $fh "LOG: Stuff happened at time: $date\n";
chomp($date = `$dateCommand && echo "sleeping for 3 seconds" && $sleepCommand && $dateCommand`);
print $fh "LOG: Following line is command output surrounded by date\n\n$date\n";
if(1){ #this is how you can put the date in error messages
chomp($date = `$dateCommand`);
die("ERROR: something happened at time: $date\n");
}
Output looks like this
$ perl date.in.logfile.pl
ERROR: something happened at time: Thu Aug 21 02:55:54 AM CDT 2025
Compilation exited abnormally with code 255 at Thu Aug 21 02:55:54
$ more logfile.txt
LOG: Stuff happened at time: Thu Aug 21 02:55:51 AM CDT 2025
LOG: Following line is command output surrounded by date
Thu Aug 21 02:55:51 AM CDT 2025
sleeping for 3 seconds
Thu Aug 21 02:55:54 AM CDT 2025
If you only wanted a specific time field instead of the entire date, you could run the date command and separate it with a regular expression like so...
#!/usr/bin/perl -w
$cmd="date";
$date=`$cmd`;
$date=~/(\w+) (\w+) (\d+) ([\d:]+) (\w+) (\w+) (\d+)/;
my ($dayOfWeek, $month, $day, $time, $meridiem, $timeZone, $year) =
($1, $2, $3, $4, $5, $6, $7);
#used printf to align columns to -11 and -8
printf("%-11s : %-8s\n", "Day of week", $dayOfWeek);
printf("%-11s : %-8s\n", "Month", $month);
printf("%-11s : %-8s\n", "Day", $day);
printf("%-11s : %-8s\n", "Time", $time);
printf("%-11s : %-8s\n", "Meridiem",$meridiem );
printf("%-11s : %-8s\n", "Timezone", $timeZone);
printf("%-11s : %-8s\n", "Year", $year);
Output looks like this...
$ perl date.pl
Day of week : Thu
Month : Aug
Day : 21
Time : 03:25:05
Meridiem : AM
Timezone : CDT
Year : 2025