How can I convert a date to epoch time?
I have a huge formatted file of the form:
开发者_高级运维29/01/2010 18:00 string1 string2 .....
30/01/2010 18:30 string3 string4 .....
...
...
dd/mm/yyyy hh:MM strings strings....
I need to perform some statistics based on the dates.
So I would like to substitute the string dd/mm/yyyy hh:MM
with epoch time in the file in order to perform simple manipulations.
I suppose that the best way is to use Perl, but I really don't know where to start. Any hints?
Just that? This quick-and-dirty one-liner should do:
perl -MPOSIX -pwe 's{^(\d{2})/(\d{2})/(\d{4}) (\d{2}):(\d{2}) }{mktime(0,$5,$4,$1,$2-1,$3-1900)." "}e;'
Feed it the file on standard input and it will output the changed version to standard output. All it does is look for lines that have "dd/mm/yyyy hh:mm " at the start, and feed the date components to the mktime
function from the POSIX
module to get a unix timestamp.
use DateTime::Format::Strptime;
my $Strp = new DateTime::Format::Strptime(
pattern => '%d/%m/%Y %H:%M',
locale => 'en_EN',
time_zone => 'UTC',
);
open INPUT, $file;
while (<INPUT>)
{
my ($date, $time, $foo) = split(' ', $_, 3);
my $dt = $Strp->parse_datetime("$date $time");
printf "%s %s", $dt->strftime('%s'), $foo;
}
close INPUT;
You could use the core module Time::Local
#!/usr/bin/perl
use 5.10.1;
use strict;
use warnings;
use Time::Local;
while(<DATA>) {
if (m#(\d+)/(\d+)/(\d+)\s+(\d+):(\d+)\s#) {
say timelocal(0,$5,$4,$1,$2-1,$3);
}
}
__DATA__
29/01/2010 18:00 string1 string2 .....
30/01/2010 18:30 string3 string4 .....
output:
1264784400
1264872600
精彩评论