如何获得文件创建&修改日期/时间? [英] How to get file creation & modification date/times?

查看:32
本文介绍了如何获得文件创建&修改日期/时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本需要根据文件创建做一些事情&修改日期,但必须在 Linux 上运行 &Windows.

创建文件的最佳跨平台方式是什么?在Python中修改日期/时间?

解决方案

在 Python 3.4 及更高版本中,您可以使用面向对象的 pathlib 模块 接口,其中包括大部分 os 模块的包装器.这是获取文件统计信息的示例.

<预><代码>>>>导入路径库>>>fname = pathlib.Path('test.py')>>>assert fname.exists(), f'No such file: {fname}' # 检查文件是否存在>>>打印(fname.stat())os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=129581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1295815642342534234234

有关 os.stat_result 包含的内容的更多信息,请参阅 文档.对于你想要的修改时间 fname.stat().st_mtime:

<预><代码>>>>导入日期时间>>>mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime)>>>打印(分钟)datetime.datetime(2018, 10, 17, 10, 49, 0, 249980)

如果您想要 Windows 上的创建时间,或 Unix 上最近的元数据更改,您可以使用 fname.stat().st_ctime:

<预><代码>>>>ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime)>>>打印(时间)datetime.datetime(2018, 4, 11, 16, 57, 52, 151953)

这篇文章有更多关于 pathlib 模块的有用信息和示例.

I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.

What's the best cross-platform way to get file creation & modification date/times in Python?

解决方案

In Python 3.4 and above, you can use the object oriented pathlib module interface which includes wrappers for much of the os module. Here is an example of getting the file stats.

>>> import pathlib
>>> fname = pathlib.Path('test.py')
>>> assert fname.exists(), f'No such file: {fname}'  # check that the file exists
>>> print(fname.stat())
os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272)

For more information about what os.stat_result contains, refer to the documentation. For the modification time you want fname.stat().st_mtime:

>>> import datetime
>>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime)
>>> print(mtime)
datetime.datetime(2018, 10, 17, 10, 49, 0, 249980)

If you want the creation time on Windows, or the most recent metadata change on Unix, you would use fname.stat().st_ctime:

>>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime)
>>> print(ctime)
datetime.datetime(2018, 4, 11, 16, 57, 52, 151953)

This article has more helpful info and examples for the pathlib module.

这篇关于如何获得文件创建&amp;修改日期/时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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