Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert text date to timestamp?

Tags:

perl

How to convert date in text format:

23.10.2011  11:35:00

to timestamp ?

like image 745
Bdfy Avatar asked Oct 11 '11 13:10

Bdfy


People also ask

How do I convert text to date?

The DATEVALUE function in Excel converts a date in the text format to a serial number that Excel recognizes as a date. So, the formula to convert a text value to date is as simple as =DATEVALUE(A1) , where A1 is a cell with a date stored as a text string.

How do you convert date to time?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.


2 Answers

Using Time::Local , you can do:

use Time::Local;

my $date = '23.10.2011  11:35:00';
my ($mday,$mon,$year,$hour,$min,$sec) = split(/[\s.:]+/, $date);
my $time = timelocal($sec,$min,$hour,$mday,$mon-1,$year);
print $time,"\n",scalar localtime $time;

Output:

1319362500
Sun Oct 23 11:35:00 2011
like image 143
Toto Avatar answered Sep 18 '22 13:09

Toto


I'd look into DateTime and the parsing modules.

perl -MDateTime::Format::Strptime -le'$strp = DateTime::Format::Strptime->new( pattern => "%d.%m.%Y  %T", time_zone => "local"); $dt = $strp->parse_datetime("23.10.2011  11:35:00"); print $dt->epoch'
1319384100 at -e line 1.

Same as above, but not a one-liner:

use DateTime::Format::Strptime;
my $strp = DateTime::Format::Strptime->new(
   pattern => '%d.%m.%Y  %T',
   time_zone => 'local',
);
my $dt = $strp->parse_datetime('23.10.2011  11:35:00');
print $dt->epoch;
like image 27
gpojd Avatar answered Sep 20 '22 13:09

gpojd