Getting the difference between two Time :: Piece objects

I have a code:

use Time::Piece;
use Time::Seconds;

my $timespan = $latest_time - $timestamp;

print $latest_time . "\n";
print $timestamp . "\n";
print $timespan->minutes;

where $ last_time = Time :: Piece-> new; and $ timestamp = Time :: Piece-> strptime ();

and I get the results:

Thu Mar 27 09:40:19 2014
Thu Mar 27 09:40:00 2014
-479.683333333333

Something went wrong? should be 0 minutes per $ timespan, right? Where is -479 from?

+1
source share
2 answers

Reproduction of the "error"

This issue occurs because strptime uses UTC instead of the local time zone. This can be demonstrated in the following code, which takes the current time, prints it, then repeats it and shows the difference:

use strict;
use warnings;

use Time::Piece;

my $now = Time::Piece->new();
print $now->strftime(), "\n";
my $fmt = "%Y-%m-%d %H:%M:%S";

my $nowstr = $now->strftime($fmt);
my $parsed = Time::Piece->strptime("$nowstr", $fmt);
print "($nowstr)\n";
print $parsed->strftime(), "\n";

my $diff = $now - $parsed;
print $diff->hours, " hours difference\n";

Outputs:

Wed, 26 Mar 2014 21:42:08 Pacific Daylight Time
(2014-03-26 21:42:08)
Wed, 26 Mar 2014 21:42:08 UTC
7 hours difference

One hacky solution is to get parsed read time as local

, , perl. strptime : $now->strptime.

my $nowstr = "2014-03-26 21:51:00";   #$now->strftime($fmt);
my $parsed = $now->strptime("$nowstr", $fmt);   #Time::Piece->strptime("$nowstr", $fmt);
print "($nowstr)\n";
print $parsed->strftime(), "\n";

my $diff = $now - $parsed;
print $diff->hours, " hours difference\n";

, strptime , , , 6 . :

Wed, 26 Mar 2014 21:57:00 Pacific Daylight Time
(2014-03-26 21:51:00)
Wed, 26 Mar 2014 21:51:00 Pacific Standard Time
0.1 hours difference

c_islocal $now. $now localtime ->new(), gmtime, .

, , DST , - . , strptime, _mktime new.

, -, Time::Piece, .

+3

strftime("%H:%M:%S %Z") $latest_time $timestamp, , $latest_time - $timestamp , , . ​​ Time:: Piece.

, , Time::Piece->new; , .

Time::Piece->new, , Time::Piece->strptime(); . , .

0

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


All Articles