简体   繁体   English

如何从 perl 中的 fstat 获取本地 mtime?

[英]How do I get local mtime from fstat in perl?

Is it possible to get/convert the mtime from fstat to local time in perl?是否可以在 perl 中将 mtime 从 fstat 获取/转换为本地时间?

If I do如果我做

my $stat = stat($file);
my $mtime = $stat->mtime;
my $time = Time::Piece->strptime($time, '%s');

and then format that time to - say - '%Y%m%d%H%M' I get a time that's 1 hour earlier than the time I see on ls -l , as I live in and my machine is configured to GMT+1.然后将该时间格式化为 - 比如说 - '%Y%m%d%H%M'我得到的时间比我在ls -l上看到的时间早 1 小时,因为我住在那里,我的机器配置为 GMT +1。

I would instead like to have an output that's consistent with ls -l我想要一个与ls -l一致的输出

so that if所以如果

> ls -l foo.txt
> -rw-r--r--@  1 somuser  296108113    163673 Mar 31 16:43 foo.txt

the output is 202003311643 instead of - like I get now - 202003311443 (GMT+1 and DST).输出是202003311643而不是 - 就像我现在得到的 - 202003311443 (GMT+1 和 DST)。

Is there a way to handle this in a straightforward way (ie: so that I don't have to manually adjust for the timezone, or DST)?有没有办法以直接的方式处理这个问题(即:这样我就不必手动调整时区或 DST)?

A Time::Piece object can represent either a local time or a UTC time. Time::Piece 对象可以表示本地时间或 UTC 时间。 The following creates an object representing a UTC time:下面创建一个表示 UTC 时间的对象:

my $time = Time::Piece->strptime($mtime, '%s');

The equivalent for creating a local time is创建本地时间的等价物是

use Time::Piece;
my $time = localtime->strptime($mtime, '%s');

or或者

my $time = Time::Piece::localtime->strptime($mtime, '%s');

That said, using strptime is unnecessary here.也就是说,在这里使用strptime是不必要的。 One can simply use一个可以简单地使用

use Time::Piece;
my $time = localtime($mtime);

or或者

my $time = Time::Piece::localtime($mtime);

to get the correct Time::Piece object.获得正确的 Time::Piece 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM