Skip to main content
 首页 » 编程设计

python之如何在 Python 中获取文件的 ctime 和/或 mtime,包括时区

2025年05月04日3652php

基于这个相关question和 answer我问,很明显 datetime.fromtimestamp(os.path.getctime()) 在 Python 3.4 中不返回时区感知日期时间对象,但是,根据一些调查,我'我们还发现 HFS+ 文件系统(例如)上的 OS X 10.9 似乎 与 ctimes 一起维护时区(除非 gls 从我的本地时区和夏令时推断时区):

$ gls -l --full-time -c 
 
-rw-------  1 myuser staff 538 2015-01-04 17:12:57.000000000 +0100 fileone 
-rwxr-xr-x 17 myuser staff 578 2015-05-20 06:41:07.000000000 +0200 filetwo 

(我正在使用 the GNU version of ls )

如何从 ctime 获取时区并将其插入/组合到日期时间对象中?

(我也希望 mtime 有相同的答案,我想它会是相似的)。

请您参考如下方法:

ctime 和 mtime 都可以作为“纪元以来的秒数”(time.time() 返回的值)使用。

要获取本地时区,您可以使用 tzlocal module :

#!/usr/bin/env python 
import os 
from datetime import datetime 
from tzlocal import get_localzone # $ pip install tzlocal 
 
local_timezone = get_localzone() 
aware_dt = datetime.fromtimestamp(os.path.getctime(path), local_timezone) 

您可能会看到时区信息,因为 ls 使用本地时区将时间戳转换为具有时区偏移的相应分割时间。