问题描述
我正在尝试使用Cygwin中的Python 3.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
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时间戳早 1小时?实际使用的是哪个时区?
解决方法
确保在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。