Perl: Parse Linux log time strings
Linux has a common date/time format used in logs that looks like May 4 01:04:16
. Often I will need to parse that into a unixtime so I wrote a function to do it so I won't have to reinvent the wheel next time:
use Time::Piece;
my $epoch = linux_timestr("May 4 01:04:16");
sub linux_timestr {
my $time_str = shift();
# Since this string type doesn't include the year we append the current
# year to make the calculations correct. Otherwise we get 1970
my $year = (localtime())[5] + 1900;
$time_str .= " $year";
my $format = "%b %d %H:%M:%S %Y";
my $x = localtime->strptime($time_str, $format);
return $x->epoch();
}
Other common formats are cdate and ISO 8601
# cdate
my $x = localtime->strptime("Sat May 8 21:24:31 2021", "%a %b %d %H:%M:%S %Y");
# ISO 8601
my $y = localtime->strptime("2000-02-29T12:34:56", "%Y-%m-%dT%H:%M:%S");