在Perl中,如何获取文件的时间戳并立即检查?
谢谢。
Alex
答案 0 :(得分:2)
如果您确切地告诉我们您尝试过的以及您遇到的问题,请提供帮助。
您可以使用File::stat获取有关文件的信息。
use File::stat;
my $stat = stat($file);
通过在$stat
对象上调用三种不同的方法,您可以获得三个不同的时间戳。
my $ctime = $stat->ctime; # inode change time
my $atime = $stat->atime; # last access time
my $mtime = $stat->mtime; # last modification time
我想你可能想要$mtime
,但我不能确定。每个变量都包含自系统时代以来的秒数(几乎可以肯定是1970年1月1日00:00)。
您可以使用Time::Piece将这些纪元值转换为有用的对象。
use Time::Piece;
my $file_date = localtime($mtime);
您可以将其与当前日期进行比较。
if ($file_date->date eq localtime->date) {
# file was created today
}
答案 1 :(得分:2)
我会(可能)使用-M
:
http://perldoc.perl.org/functions/-X.html
-M脚本开始时间减去文件修改时间,以天为单位。
这意味着您可以:
if ( -M $filename < 1 ) {
#if file is less than a day old
}
当然,这仅适用于脚本启动,而不是现在,因此不适合长时间运行的脚本。
答案 2 :(得分:0)
哦,看,哦。 mtime是一个很大的数字。多少 。 。分钟/小时/天/年是这样的? (dc是命令行计算器。)use File::stat; # we don't need anything but mtime # my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, # $atime, $mtime, $ctime, $blksize, $blocks) = stat($filename); my $ts = stat($filename)->mtime; print "ts:$ts"; print " date/time " . localtime($ts) . "\n"; ts:1469028287 date/time Wed Jul 20 16:24:47 2016
$ dc
1469028287
60/p
24483804
60/p
408063
24/p
17002
356.25/p
47
47岁。 (使用dc整数除法获得/丢失一段时间)。现在(8月8日星期一10:58 2016年) - 46(其中46 = ish ahem = 47)年= 1/1/1970 00:00:00 = unix日期/时间戳纪元。< / p>
# localtime returns array or string depending on context. my $time = localtime; my @time = localtime; print "time:$time\n"; print "time array: " . join (":", (@time)) . "\n"; my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime; use Time::Local; my $btime = timelocal(0,0,0,$mday,$mon,$year); my $etime = timelocal(59,59,23,$mday,$mon,$year); print "btime:$btime " . localtime($btime) . " etime:$etime " . localtime($etime) . "\n"; print "year:$year\n"; time:Mon Aug 8 11:40:33 2016 time array: 33:40:11:8:7:116:1:220:1 btime:1470610800 Mon Aug 8 00:00:00 2016 etime:1470697199 Mon Aug 8 23:59:59 2016 year:116
if (($ts >= $btime) && ($ts <= $etime)) { print "File time $ts (".localtime($ts).") is TODAY.\n"; } else { print "File time $ts (".localtime($ts).") is NOT today.\n"; if ($ts < $btime) { print "File is BEFORE today. $ts < $btime\n"; } elsif ($ts > $etime) { print "File is in FUTURE. $ts > $etime\n"; } else { print "KERBOOM.\n" } }
答案 3 :(得分:0)
其中一个ways如何将其浓缩为一行:perl -e '$f = shift; printf "file %s updated at %s\n", $f, scalar localtime((stat $f)[9])' file
。