taiko
taiko

Reputation: 448

PERL How to convert localtime format to unixtime

Can anyone helpme with this? I have a time value in a the logfilefile which has following format:

Tue Aug 28 09:50:06 2012

I need to convert this time value into unixtime.

regards

Upvotes: 2

Views: 2329

Answers (3)

Sean Bright
Sean Bright

Reputation: 120644

This works for me (requires DateTime::Format::Strptime):

#!/usr/bin/perl

use strict;
use warnings;

use DateTime::Format::Strptime;

my $strp = DateTime::Format::Strptime->new(
  pattern   => '%a %b %d %H:%M:%S %Y',
  locale    => 'en_US',
  time_zone => 'local',  # Or even something like 'America/New_York'
  on_error  => 'croak',
);

my $dt = $strp->parse_datetime('Tue Aug 28 09:50:06 2012');

print $dt->epoch() . "\n";

Upvotes: 2

Borodin
Borodin

Reputation: 126722

Your best choice here is Time::Piece, which is a core module and so shouldn't need installing. It has an strptime method for parsing time/date strings and an epoch method for returning the Unix epoch time

It is convenient to roll this into a subroutine as shown here

use strict;
use warnings;

use Time::Piece ();

print date_to_epoch('Tue Aug 28 09:50:06 2012'), "\n";

sub date_to_epoch {
   return Time::Piece->strptime($_[0], '%a %b %d %T %Y')->epoch;
}

output

1346147406

Upvotes: 6

Brian Showalter
Brian Showalter

Reputation: 4349

Use the strptime function in the Time::Piece module to parse the date, then use the strftime function to return the Unix timestamp.

use Time::Piece;
$parsed = Time::Piece->strptime("Tue Aug 28 09:50:06 2012", "%a %b %e %T %Y");
$unixtime = $parsed->strftime("%s");

Upvotes: 0

Related Questions