从stat().st_mtime到datetime? [英] From stat().st_mtime to datetime?

查看:301
本文介绍了从stat().st_mtime到datetime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将从stat()调用中检索到的修改时间转换为datetime对象的最惯用/最有效的方法是什么?我提出了以下内容(python3):

What is the most idiomatic/efficient way to convert from a modification time retrieved from stat() call to a datetime object? I came up with the following (python3):

from datetime import datetime, timedelta, timezone
from pathlib import Path

path = Path('foo')
path.touch()
statResult = path.stat()
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
modified = epoch + timedelta(seconds=statResult.st_mtime)
print('modified', modified)

似乎回合,我不得不在那里硬编码Unix时代,这有点令人惊讶.还有更直接的方法吗?

Seems round a bout, and a bit surprising that I have to hard code the Unix epoch in there. Is there a more direct way?

推荐答案

尝试 datetime.fromtimestamp(statResult.st_mtime)

例如

import datetime

mod_timestamp = datetime.datetime.fromtimestamp(path.getmtime(<YOUR_PATH_HERE>))

这篇关于从stat().st_mtime到datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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