Perl 为什么可以';我不能减去3倍吗?
我刚刚更新了OP,因为我打字打错了。 这个剧本Perl 为什么可以';我不能减去3倍吗?,perl,time,Perl,Time,我刚刚更新了OP,因为我打字打错了。 这个剧本 #!/usr/bin/perl use warnings; use strict; use Time::Piece; my $t1 = Time::Piece->strptime( '10:15', '%H:%M' ); my $t2 = Time::Piece->strptime( '17:30', '%H:%M' ); my $t3 = Time::Piece->strptime( '7:24', '%H:%M' ); m
#!/usr/bin/perl
use warnings;
use strict;
use Time::Piece;
my $t1 = Time::Piece->strptime( '10:15', '%H:%M' );
my $t2 = Time::Piece->strptime( '17:30', '%H:%M' );
my $t3 = Time::Piece->strptime( '7:24', '%H:%M' );
my $t = $t2 - $t1 - $t3;
print int($t->hours) . ":" . $t->minutes%60 . "\n";
将输出
Can't use non Seconds object in operator overload at /usr/lib/perl/5.14/Time/Seconds.pm line 65.
正确答案是-0:09
,即0小时零九分钟
问题
我怎样才能减去3次呢?Time::Piece
或Time::Seconds
能为我做int
和模数吗,这样我就不用做了?这句话:
my $t = $t2 - $t1 - $3;
应该是
my $t = $t2 - $t1 - $t3;
你不能从持续时间中减去时间。例如,九分钟减去一点钟是没有意义的 这里有
$t1
等于10:15am
,$t2
等于17:30
或5:30pm
。因此,$t2-$t1
是它们之间的时间,即7.25小时
现在您正试图从该结果中减去$t3
,即7:24am
。但是7.25小时减去上午7:24是一个持续时间减去一天中的某个时间,这是不可能做到的。这就是你得到信息的原因
无法使用非秒对象
,因为您试图从时间::秒
对象(持续时间)中减去时间::片段
对象(一天中的一个时间)
更新 如果您在持续时间内工作,那么您需要像这样始终使用
Time::Seconds
模块
use strict;
use warnings;
use Time::Seconds;
my $t1 = Time::Seconds->new(10 * ONE_HOUR + 15 * ONE_MINUTE); # 10:15
my $t2 = Time::Seconds->new(17 * ONE_HOUR + 30 * ONE_MINUTE); # 17:30
my $t3 = Time::Seconds->new( 7 * ONE_HOUR + 24 * ONE_MINUTE); # 7:24
my $t = $t2 - $t1 - $t3;
print $t->minutes, "\n";
输出
-9
-9
或者您可能更愿意从Time::Piece
对象中减去午夜00:00
,如下所示
use strict;
use warnings;
use Time::Piece;
use constant MIDNIGHT => Time::Piece->strptime('00:00', '%H:%M');
my $t1 = Time::Piece->strptime( '10:15', '%H:%M' );
my $t2 = Time::Piece->strptime( '17:30', '%H:%M' );
my $t3 = Time::Piece->strptime( '7:24', '%H:%M' );
$_ -= MIDNIGHT for $t1, $t2, $t3;
my $t = $t2 - $t1 - $t3;
print $t->minutes;
它还输出-9
请注意使用$t->minutes%60
中的模数无法得到所需的值,因为-9%60
是51
分钟
更新2 另一个选项是编写一个使用前面任一选项的助手例程。这个例子有一个子例程
new\u duration
,它使用Time::Piece->strtime
解析传入的字符串,然后在返回结果Time::Seconds
对象之前减去午夜
use strict;
use warnings;
use Time::Piece;
use Time::Seconds;
use constant MIDNIGHT => Time::Piece->strptime('00:00', '%H:%M');
my $t1 = new_duration('10:15');
my $t2 = new_duration('17:30');
my $t3 = new_duration( '7:24');
my $t = $t2 - $t1 - $t3;
print $t->minutes;
sub new_duration {
Time::Piece->strptime(shift, '%H:%M') - MIDNIGHT;
}
输出
-9
-9
$t2-$t1
返回一个Time::Seconds
对象,在该对象上未定义-
运算符。$3
和$t3
不是一回事。发现得很好,这解释了为什么我没有得到想要重现的原始错误。现在脚本产生“正确”错误。这些时间是天还是持续时间?你想(用英语)做什么?$t2有时是不是总共有三个持续时间($t
、$t1
和$t3
),而您正试图获得第三个持续时间?是的,我在脚本中输入了一个错误,但更正后,当减去3次时,我收到一条错误消息。$t2-$t1
是一个时间::秒
对象,您不能从中减去另一个时间::片段
对象,因此您的答案不能回答OP的问题。那么有没有简单的方法将'10:15'
转换为时间::秒->新的(10*3600+15*60)
?在实行夏时制的一天中,减去午夜是正确的吗?另外,如果我的脚本运行超过午夜或几天会怎么样?Time::Piece
忽略夏令时,并且原始代码中存在跨越午夜边界的时间间隔问题。如果你只能指定时间,那么差异永远不会超过24小时。@aschepler:我认为你应该发布一个新的问题和你真正的问题,而不是一点一点地修改你的问题。我没有任何原始代码或真正的问题。只是试着了解我能做的,并帮助确保答案是准确和有用的。