Path().stat().st_时区?

2024-04-18 01:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Cygwin中的Python3.8获取文件的上次修改时间

因此,如果我这样做stat .profile,我会得到:

  File: .profile
  Size: 1236            Blocks: 4          IO Block: 65536  regular file
Device: 46e61a95h/1189485205d   Inode: 8162774324632653  Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (197609/   pepol)   Gid: (197609/   pepol)
Access: 2020-09-14 15:16:04.773101900 +0700
Modify: 2020-09-14 15:15:21.977809000 +0700
Change: 2020-09-14 15:16:04.055602500 +0700
 Birth: 2020-09-14 15:16:04.052652900 +0700

但是如果我尝试使用Python获取文件的时间戳:

from pathlib import Path
from datetime import datetime

p1 = Path(".profile")
p1st = p1.stat()
dts = datetime.fromtimestamp(p1st.st_mtime)
print(str(dts))

我得到了这个“天真”(无时区)的结果:

2020-09-14 09:15:21.977809

现在我感到困惑的是:

  • stat输出所示,我的时区是UTC+07:00
  • 我的国家没有DST
  • Windows的时区设置正确
  • 15:15:21.977809000 +0700相当于08:15:21.977809000 +0000

为什么pathlib.Path().stat()获取的时间戳比UTC时间戳的时间戳早了一个小时?它实际使用的时区是什么


Tags: 文件pathfromimportdatetimeaccess时间profile
1条回答
网友
1楼 · 发布于 2024-04-18 01:52:53

确保在cygwin中使用Cygwin的Python。您可以通过$which python3检查cygwin使用的Python版本。应该返回,例如/usr/bin/python3

  • 如果在Cygwin中使用Windows Python安装,它将无法正确确定计算机的时区(操作系统设置)(Windows Python配置为在Windows上执行此操作,而不是在Unix环境中,反之亦然)

旁注,由于pathlib.Path().stat()返回的时间戳是POSIX时间戳,因此您可以使用例如datetime.fromtimestamp(p1st.st_mtime, tz=timezone.utc)直接获取UTC

相关问题 更多 >