Python 从 stat().st_mtime 到 datetime?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39359245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:10:49  来源:igfitidea点击:

From stat().st_mtime to datetime?

pythonpython-3.xdatetimestatpathlib

提问by Travis Griggs

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

stat()调用检索到的修改时间转换为datetime对象的最惯用/最有效的方法是什么?我想出了以下内容(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)

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?

似乎差不多,有点令人惊讶的是我必须在那里对 Unix 纪元进行硬编码。有没有更直接的方法?

回答by Take_Care_

Try datetime.fromtimestamp(statResult.st_mtime)

尝试 datetime.fromtimestamp(statResult.st_mtime)

e.g.

例如

import datetime

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

回答by Sam Shleifer

This works for me if you want a readable string:

如果你想要一个可读的字符串,这对我有用:

import datetime
mtime = path.stat().st_mtime
timestamp_str = datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d-%H:%M')