I want to display time in the same format as is displayed by the linux diff
command.
D:\>diff -dub old.cfg new.cfg
--- old.cfg 2019-05-15 15:03:14.289950700 +0530
+++ new.cfg 2019-05-14 16:07:21.119695300 +0530
I want to show last modified time of a file as 2019-05-15 15:03:14.289950700 +0530
.
I used stat
but I am not getting that nanosecond part. Alo, need timezone in given format. I tried Time::HiRes
too, but couldn't get.
my $dt = strftime("%Y-%m-%d %H:%M:%S", localtime((stat($old_file))[9]));
It returns: 2019-05-15 15:03:14
. Can you please help me to append the other info?
To see the access time for a file with ls , append the -u option in your command. In this case, our access time is the same as the file's modified time, which is normal for files that have not been accessed since they were last saved.
Modified Time. The modified timestamp contains the time the file's data has been changed. It means when we make changes to the actual contents of the file, the file system will update the modification time.
I must first say, that's not going to be accurate. Even as your hardware likely supports nanosecond resolution by the time it gets back to software it's hundreds of times off. (With a file's timestamp, presumably used only as relative to other files, that may be less important.)
Having said that, the only way I find to claim nanoseconds is to use system's tools, so stat
my ($ts) = grep { /^\s*Access: [0-9]{4}/ } qx(stat $file);
$ts =~ s/^\s*Access:\s+//;
or, using map
also as a filter
my ($ts) = map { /^\s*Access:\s+([0-9]{4}.*)/ ? $1 : () } qx(stat $file);
One problem here, of course, is that we have to parse output; so see your man pages and test your stat
, and don't hope for much portability. Watch for system changes as output format of programs may change. But I don't find nanoseconds claim in Perl.
For reference, on my CentOS 7 (under both bash
and tcsh
)
perl -we'$f=shift; print grep { /^\s*Access: [0-9]{4}/ } qx(stat $f)' file
prints, for a random file
Access: 2019-05-15 13:21:57.723987422 -0700
Once again, the "nano"seconds aren't accurate at all.
Another option, for perhaps more reliable output parsing, is to use ls
with its --full-time
my $ts = join ' ', (split ' ', qx(ls --full-time $file))[5..7];
As always, when running external commands build your variables with care and quote and escape appropriately. A good tool is String::ShellQuote. Or, better avoid the shell altogether unless it's specifically needed. Best do all this using a module for running external tools.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With