如何获取 Python 中文件的 ctime and/or 时间(包括时区)?

How can I get the ctime and/or mtime of a file in Python including timezone?

基于这个相关的 and 我问过,Python 3.4 中的 datetime.fromtimestamp(os.path.getctime()) 显然不是 return 时区感知日期时间对象,但是,根据一些调查,我还发现 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 获取时区并将其 insert/combine 放入日期时间对象?

(我也想要相同的时间答案,我想它会相似)。

ctime 和 mtime 都可用 "seconds since epoch"(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 使用本地时区将时间戳转换为具有时区偏移的相应细分时间。

如果只想依赖Python标准库,只能使用tzinfo的timezone子类:

tz = datetime.timezone(datetime.timedelta(seconds=-time.timezone), time.tzname[0]) \
    if (time.daylight == 0 || time.localtime(os.path.getctime(path)).tm_isdst == 0) \
    else datetime.timezone(datetime.timedelta(seconds=-time.altzone), time.tzname[1])
dt = datetime.fromtimestamp(os.path.getctime(path), tz)

那么你可以(在法国):

>>> dt
datetime.datetime(2015, 6, 9, 13, 43, 3, 791255, tzinfo=datetime.timezone(datetime.timedelta(0, 7200), 'Paris, Madrid (heure d\x92été)'))
>>> dt.utctimetuple()
time.struct_time(tm_year=2015, tm_mon=6, tm_mday=9, tm_hour=11, tm_min=43, tm_sec=3, tm_wday=1, tm_yday=160, tm_isdst=0)

当然,mtime 的工作方式完全一样

您应该参考 J.F. Sebastian's post。这是摘录:

要以解决 time.daylight 问题的方式获取当前的 UTC 偏移量,并且即使 tm_gmtoff 不可用也能正常工作,可以使用 [this]:

import time
from datetime import datetime

ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
              datetime.utcfromtimestamp(ts)).total_seconds()

这对我有用:

import os, datetime, time

modified_time = os.path.getmtime(file)
mtime_obj = datetime.datetime(*time.localtime(modified_time)[:6])
# (or)
mtime_obj = datetime.datetime.fromtimestamp(modified_time)
print(mtime_obj.strftime('%Y-%m-%d_%H-%M-%S'))

没有外部包。只是标准 python 库。 (Python 3.6)