将时间戳字符串解析为整数并减去雇用时间戳

时间:2019-01-23 18:12:27

标签: perl

Perl的新手。我有一个格式为20190123120445的字符串,即YYYYMMDDHHMISS。在perl中,如何将其转换为时间戳,该时间戳可用于减去从Time :: Hires时间时间戳生成的另一个时间戳。我知道时间戳是不同的分辨率,并且会假定第一个时间戳从0 ms开始。

我可以将时间戳转换为DateTime对象,但是尝试减去hirers计时器值会导致错误。

如何将第一个字符串转换为与时间戳相同分辨率的时间戳,以便我可以减去这些值并获得增量?还是有一个更明显的解决方案?

use Time::Hires;
use Date::Parse;

my $parser = DateTime::Format::Strptime->new(
    pattern => '%Y%m%d%H%M%S',
    on_error => 'croak',
);

my $dt = $parser->parse_datetime($args->{EVENTCREATEDTIMESTAMP});
my $delta = time - $dt;

如果我尝试执行此操作,则会出现此错误

Bad message vendor or subscription: Cannot subtract 1548265276 from a
DateTime object (DateTime=HASH(0x28e10d98)). Only a DateTime::Duration
or DateTime object can be subtracted from a DateTime object.

1 个答案:

答案 0 :(得分:3)

要提交它作为正确的答案:要获得与time相同的纪元时间戳,请在DateTime对象上调用epoch方法。您可以轻松减去纪元时间戳,以秒为单位,然后将其转换为较大的面额。 Time::Seconds为此提供了有用的常量。

use strict;
use warnings;
use Time::Seconds;
my $diff = time - $dt->epoch;
my $diff_hours = $diff / ONE_HOUR;

如果您想要日历持续时间差异,事情会变得复杂。这是因为对夏令时和leap秒这样的总的东西没有静态的定义,例如“一个月”甚至“一天”和“一分钟”。因此,差异取决于时区以及绝对的开始和结束时间。解决此问题的最简单方法是将纪元时间戳转换为DateTime对象,并让DateTime为您完成工作。

my $dt_time = DateTime->from_epoch(epoch => time);
# Each of the following returns DateTime::Duration objects with different measures of calendar time
my $diff_duration = $dt_time->subtract_datetime($dt); # months, days, minutes, seconds, nanoseconds
my $diff_days = $dt_time->delta_days($dt); # full days
my $diff_ms = $dt_time->delta_ms($dt); # minutes and seconds
my $diff_abs = $dt_time->subtract_datetime_absolute($dt); # seconds and nanoseconds

可以使用in_units方法或将其传递给DateTime::Format::Duration来检索生成的DateTime :: Duration对象的各个组成部分。 subtract_datetime_absolute方法是计数leap秒的唯一方法-纪元时间戳有效地忽略了它们,与其他方法相比,“分钟”可能不长60秒。