doudy_05
doudy_05

Reputation: 61

How do calculate and convert localtime to unix time stamp in Perl

My script is :

   use warnings;
   use strict;

my $start_time = localtime();
     $sql = "INSERT into Table1, Select (VAr1, Var2, Var3 ...........)";
my $end_time = localtime();
my $run_time = ($end_time - $start_time);

my @months = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
my ($sec, $min, $hour, $day,$month,$year) = (localtime($run_time))[0,1,2,3,4,5]; 
print "Unix time ".$run_time." converts to ".$months[$month]." ".$day.", ".($year +=1900);
print " ".$hour.":".$min.":".$sec."\n";

When I run it, I don't get the desire output.

Unix time 648 converts to Jan , 1900 ::

I need to get hour:min:sec the time the script took to calculate the insert into the table.

Thank you

Upvotes: 0

Views: 326

Answers (2)

ikegami
ikegami

Reputation: 386676

$run_time isn't a timestamp (a number of seconds since epoch representing a date-time), so it makes no sense to pass it to localtime.

my $s = $run_time % 60;  $run_time = ($run_time - $s) / 60;
my $m = $run_time % 60;  $run_time = ($run_time - $m) / 60;
my $h = $run_time;

my $formatted_run_time = sprintf "%d:%02d:%02d", $h, $m, $s;

You can get fancier too:

my $formatted_run_time =
   $h ? sprintf "%d:%02d:%02d", $h, $m, $s
   $m ? sprintf "%d:%02d", $m, $s
   $s;

Upvotes: 2

simbabque
simbabque

Reputation: 54381

localtime is used to convert unix timestamps to a human-readable time (or a list of parts of it), but you are giving it a duration in seconds. It will treat it like a timestamp, and give you a very low date and time.

print scalar localtime 648;
# gives Thu Jan  1 01:10:48 1970

Your code gives the following output:

Unix time 648 converts to Jan 1, 1970 1:10:48

The problem is that you are essentially mixing two concepts here.

You might want to use the Benchmark module instead, which is intended for this exact purpose.

use strict;
use warning;
use Benchmark;

my $t0 = Benchmark->new;

# do your database stuff here

my $t1 = Benchmark->new;
my $td = timediff($t1, $t0);
print "the code took:",timestr($td),"\n";

If you are on a Linux or Unix, you can also use the time program to meassure the overall runtime of your program.

$ time perl foo.pl
real    0m2.241s
user    0m2.236s
sys 0m0.000s

$

Upvotes: 1

Related Questions