开发者

perl- help formatting a timestamp

开发者 https://www.devze.com 2023-01-12 02:49 出处:网络
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:

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? T开发者_开发技巧hanks.


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');


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消