gpt4 book ai didi

python - Path().stat().st_mtime 时区?

转载 作者:行者123 更新时间:2023-12-05 04:58:40 28 4
gpt4 key购买 nike

我正在尝试在 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

但是如果我尝试使用 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
  • 我的国家没有夏令时
  • 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。

关于python - Path().stat().st_mtime 时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63881543/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com