views:

75

answers:

4

I am reading in log data with the following time stamp format:

Sat Aug 07 04:42:21 2010

I want to convert it to something like this:

20100807044221

What is the best way to do this in perl? Thanks.

+1  A: 

This is what Date::Parse is for.

You specify language and corresponding date format, like (copied from the documentation):

        $lang = Date::Language->new('German');
        $lang->str2time("25 Jun 1996 21:09:55 +0100");

The above will return "epoch" value, AKA unix time value (what you need).

Edit: regarding your post, you only need the canonical date string like yyyy-mmm-ddd etc., therefore you can invoke POSIX::strftime for that. Furthermore, your date format is default, so you won't need the language call:

...
use Date::Parse;
use POSIX qw(strftime);

my $sec = str2time('Sat Aug 07 04:42:21 2010');
my $ymd = strftime "%Y%m%d%H%M%S", gmtime($sec);

print "$ymd\n";
...

Result:

20100807024221

Regards

rbo

rubber boots
I thought he wanted the epoch at first too, but he is actually looking for YYYYMMDDhhmmss
cam
@cam: Thanks, I missed that (and edited the posting).
rubber boots
+1  A: 

Date::Parse may not be installed on all your systems, so you may want to use the following snippet:


my ($sec, $min, $hour, $mday, $mon, $year) = localtime();

my $timestamp = sprintf( "%04d%02d%02d%02d%02d%02d",
                          $year+1900, $mon+1, $mday, $hour, $min, $sec);

print("Timestamp: $timestamp\n");

Timestamp: 20100819135418

Daniel Coupal
Thanks, that works great. Yes, no Date::Parse. Using localtime primarily for date lookups.
jda6one9
Doesn't help with the parsing part of the question, though.
mscha
A: 

perl -MPOSIX -le'print strftime "%Y%m%d%H%M%S", localtime'

never mind, you need to parse it first. that'll just print it out in your format.

sreservoir
+5  A: 

Use Time::Piece. (Core module since Perl 5.10.)

#!/usr/bin/perl

use strict;
use warnings;

use Time::Piece;

my $timestamp1 = 'Sat Aug 07 04:42:21 2010';
my $time = Time::Piece->strptime($timestamp1, '%a %b %d %H:%M:%S %Y');
my $timestamp2 = $time->strftime('%Y%m%d%H%M%S');
mscha