Perl gets UTC time and gets the difference between UTC timestamps

I am looking for some help in Perl on how to do this correctly. I do not mind using the library for this.

I am pulling the UTC time stamp from mySQL database in this format: 2012-02-06 13:50:09

I need Perl to pull the current UTC time and get the difference between the two timestamps in minutes (or seconds). I did this in the Unix subprocess, but it's hard for me to get the UTC time and compare it, since the local field works in Eastern time. I would not mind doing this during Unix, but Iโ€™m not sure how to get the UTC time exactly for comparison with "last_timestamp", which is the UTC timestamp from mysql.

my $date_diff = qx(date -d "\$(date +'%F %T')" +%s) - qx(date -d "$last_timestamp" +%s); 

As always, your help is certainly appreciated and appreciated.

+4
source share
4 answers
  • Paradigm error. Unix boxes do not start in Eastern time or "work in Pacific time." Unix blocks run in โ€œseconds from the eraโ€ and have a default time zone that is used to represent time values โ€‹โ€‹to users. Once you understand this, many other useful things come for free.

  • You can make time "date" UTC using "date -u"

  • Perl time built-in function returns seconds from an era (no time zone). You can then convert this value to UTC YMDHMS values โ€‹โ€‹using the Perl gmtime built-in function. A call to gmtime without any arguments actually matches gmtime(time) .

  • Use DateTime :: Format :: MySQL to parse MySQL date and time values. You can also find DateTime . Also see http://datetime.perl.org/

+14
source

One way is to use the core Time :: Piece

 #!/usr/bin/env perl use strict; use warnings; use Time::Piece; my $when = q(2012-02-06 13:50:09); my $t = Time::Piece->strptime( $when, "%Y-%m-%d %H:%M:%S" ); print "delta seconds = ", time() - $t->strftime("%s"),"\n"; 
+2
source

Here's a solution using DateTime

 use strict; use warnings; use DateTime; my $date_str="2012-02-06 13:50:09"; my ($year,$month,$day,$hour,$min,$sec); if($date_str=~/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/) { $year=$1; $month=$2; $day=$3; $hour=$4; $min=$5; $sec=$6; } else { die "Couldn't parse timestamp $date_str\n"; } my $dt=DateTime->new( year=>$year, month=>$month, day=>$day, hour=>$hour, minute=>$min, second=>$sec, time_zone=>"UTC" ); my $now=DateTime->now; $now->set_time_zone("UTC"); my $difference=$now->delta_ms($dt); print "The difference is " . (60*($difference->minutes) + ($difference->seconds)) . " seconds\n"; 

Output:

 The difference is 2078 seconds 

which sounds right.

+1
source
  • Call time
  • Extract UNIX_TIMESTAMP (your_datetime_field) from MySQL
  • Subtract.
  • Div and mod 60.
  • sprintf ("%02d min %02d s", $delta_min, $delta_s);
0
source

Source: https://habr.com/ru/post/1395075/


All Articles