如何获取包含时区的Python文件的ctime和/或mtime?

编程入门 行业动态 更新时间:2024-10-13 00:34:23
本文介绍了如何获取包含时区的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?

本文发布于:2023-10-08 14:54:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1472953.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时区   文件   mtime   Python   ctime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!