以秒为单位的时差

Xi *_*Vix 11 perl time date date-arithmetic

在Perl程序中,我有一个包含这种格式的日期/时间的变量:

Feb 3 12:03:20  
Run Code Online (Sandbox Code Playgroud)

我需要确定该日期是否超过x秒(基于当前时间),即使这发生在午夜(例如Feb 3 23:59:00当前时间= Feb 4 00:00:30).

我发现的perl日期/时间信息令人难以置信.我可以告诉我需要使用Date :: Calc,但我找不到秒 - delta.谢谢 :)

Sjo*_*ers 20

#!/usr/bin/perl

$Start = time();
sleep 3;
$End = time();
$Diff = $End - $Start;

print "Start ".$Start."\n";
print "End ".$End."\n";
print "Diff ".$Diff."\n";
Run Code Online (Sandbox Code Playgroud)

这是一种以秒为单位查找时差的简单方法.


vmp*_*str 9

似乎有一个方便的Date :: Parse.这是一个例子:

use Date::Parse;

print str2time ('Feb 3 12:03:20') . "\n";
Run Code Online (Sandbox Code Playgroud)

以下是它的输出:

$ perl test.pl
1328288600
Run Code Online (Sandbox Code Playgroud)

这是: Fri Feb 3 12:03:20 EST 2012

我不确定解析是多么体面,但它解析你的例子就好了:)


JRF*_*son 6

本着TMTOWTDI的精神,您可以利用核心Time :: Piece:

#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $when = "@ARGV" or die "'Mon Day HH:MM:SS' expected\n";
my $year = (localtime)[5] + 1900;
my $t = Time::Piece->strptime( $year . q( ) . $when, "%Y %b %d %H:%M:%S" );
print "delta seconds = ", time() - $t->strftime("%s"),"\n";
Run Code Online (Sandbox Code Playgroud)

$ ./mydelta 2月3日12:03:20

delta seconds = 14553
Run Code Online (Sandbox Code Playgroud)

假设当前年度并取自您当地时间.


the*_*ber 3

在 Perl 中,做某事总是有不止一种方法。下面是仅使用 Perl 标准模块的一个:

#! perl -w

use strict;
use Time::Local;

my $d1 = "Feb 3 12:03:20";
my $d2 = "Feb 4 00:00:30";

# Your date formats don't include the year, so
# figure out some kind of default.
use constant Year => 2012;


# Convert your date strings to Unix/perl style time in seconds
# The main problems you have here are:
# * parsing the date formats
# * converting the month string to a number from 1 to 11
sub convert
{
    my $dstring = shift;

    my %m = ( 'Jan' => 0, 'Feb' => 1, 'Mar' => 2, 'Apr' => 3,
            'May' => 4, 'Jun' => 5, 'Jul' => 6, 'Aug' => 7,
            'Sep' => 8, 'Oct' => 9, 'Nov' => 10, 'Dec' => 11 );

    if ($dstring =~ /(\S+)\s+(\d+)\s+(\d{2}):(\d{2}):(\d{2})/)
    {
        my ($month, $day, $h, $m, $s) = ($1, $2, $3, $4, $5);
        my $mnumber = $m{$month}; # production code should handle errors here

        timelocal( $s, $m, $h, $day, $mnumber, Year - 1900 );
    }
    else
    {
        die "Format not recognized: ", $dstring, "\n";
    }
}

my $t1 = convert($d1);
my $t2 = convert($d2);

print "Diff (seconds) = ", $t2 - $t1, "\n";
Run Code Online (Sandbox Code Playgroud)

为了使其真正做好生产准备,它需要更好地处理年份(例如,当开始日期是 12 月、结束日期是 1 月时会发生什么?)和更好的错误处理(例如,如果 3 字符月份缩写拼写错误?)。

  • @xivix,对于你想要的东西来说,这不必要地复杂。[vmpstr的答案](http://stackoverflow.com/a/9134822/132382)在这里完全可行。 (3认同)