如何获取包含时区的Python文件的ctime和/或mtime? [英] How can I get the ctime and/or mtime of a file in Python including timezone?

查看:106
本文介绍了如何获取包含时区的Python文件的ctime和/或mtime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此相关的问题答案我问,很明显, datetime.fromtimestamp(os。 Python 3.4中的path.getctime())不会返回可识别时区的datetime对象,但是,根据一些调查,我还发现HFS +文件系统上的OS X 10.9(例如)好像要与ctimes一起维护时区(除非gls从我的本地时区和夏时制推断出时区):

Based on this related question and answer I asked, it has become obvious that datetime.fromtimestamp(os.path.getctime()) in Python 3.4 doesn't return a timezone-aware datetime object, However, based on some investigation, I've also discovered that OS X 10.9 on an HFS+ filesystem (for example) does seem to maintain the timezones along with ctimes (unless gls is inferring the timezone from my local timezone and daylight-savings time):

$ 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

(我正在使用 ls的GNU版本

如何从ctime中获取时区并进行插入/合并

How can I get the timezone from the ctime and insert/combine it into a datetime object?

(我也想给mtime相同的答案,我想它将是相似的。)

(I'd also like the same answer for the mtime, I assume it will be similar).

推荐答案

ctime和mtime都可以用作自纪元以来的秒数(由 time.time()返回的值) )。

Both ctime and mtime are available as "seconds since epoch" (values returned by time.time()).

要获取本地时区,可以使用 tzlocal 模块

To get the local timezone, you could use 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 使用本地时区将时间戳转换为具有时区偏移的相应细分时间。

You might see the timezone info because ls converts the timestamps into corresponding broken-down time with timezone offset using the local timezone.

这篇关于如何获取包含时区的Python文件的ctime和/或mtime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆