从文件列表中输出时间戳

Outputting timestamps from a list of files

我在为目录中的文件输出时间戳时遇到问题。想列出达到某个时间window的时间戳,目前连输出都获取不到。不确定我做错了什么并撞到墙上 atm

from datetime import datetime, timedelta
from os import scandir

DIR = "/home/user/directory"
TIME_FORMAT = "%Y-%m-%d%H:%M:%S.%fZ"


def convert_timestamps():
    """converting timestamps to human readable"""
    # timestamp = datetime.utcnow() - timedelta(days=7)
    timestamp = datetime.utcfromtimestamp
    file_times = timestamp.strftime(TIME_FORMAT)
    return file_times

def get_files():
"""getting files from dir"""
    dir_filenames = scandir(DIR)
    for filename in dir_filenames:
        if filename.is_file():
            file_stat = os.stat(str(filename))
            # info = os.stat(filename)
            print("Last Modified time: {}".format(filename.name, convert_timestamps(file_stat.st_mtime)))



if __name__ == 'main':
    get_files()

以下代码片段有效,但显然不是一个程序

DIR = "/home/user/directory"
TIME_FORMAT = "%Y-%m-%d%H:%M:%S.%fZ"


file_stat = os.stat(DIR)
timestamp = datetime.utcnow() - timedelta(days=7)
file_times = timestamp.strftime(TIME_FORMAT)
print("Last mod time are: ", file_times)

主要问题是模块名称。您需要检查 __main__,而不是 main。您也没有将任何参数传递给 convert_timestamps 函数。

此代码应该有效:

from datetime import datetime, timedelta
from os import scandir
import os

DIR = "C:/tmp"  #"/home/user/directory"
TIME_FORMAT = "%Y-%m-%d %H:%M:%S.%fZ"


def convert_timestamps(stmp):
    """converting timestamps to human readable"""
    # timestamp = datetime.utcnow() - timedelta(days=7)
    timestamp = datetime.utcfromtimestamp(stmp)
    file_times = timestamp.strftime(TIME_FORMAT)
    return file_times

def get_files():
    """getting files from dir"""
    dir_filenames = scandir(DIR)
    for filename in dir_filenames:
        if filename.is_file():
            file_stat = os.stat(filename)
            # info = os.stat(filename)
            print("{} \tLast Modified time: {}".format(filename.name, convert_timestamps(file_stat.st_mtime)))

if __name__ == '__main__':   # must be __main__
    get_files()

输出

newfile.txt     Last Modified time: 2020-07-23 03:06:20.470809Z
oktatext.png    Last Modified time: 2020-07-01 16:34:03.057133Z
output.xlsx     Last Modified time: 2020-08-03 14:38:47.973999Z
python.png      Last Modified time: 2020-06-29 14:33:03.803685Z
pythonlogo.jpg  Last Modified time: 2020-07-06 02:53:09.642297Z
SomeFile2.dll   Last Modified time: 2020-08-01 21:26:42.978218Z

建议查看 pathlib and/or glob 以简化操作。在这里,例如

from datetime import datetime, timezone
from pathlib import Path

DIR = "/home/user/directory"
TIME_FORMAT = "%Y-%m-%d%_H:%M:%S.%fZ"

dir_content = list(Path(DIR).glob('*')) # give me anything...

for p in dir_content:
    if p.is_file():
        timestring = (
               datetime.fromtimestamp(p.stat().st_mtime, timezone.utc)
               .strftime(TIME_FORMAT)
               )
        print(f"{p.name} \tLast Modified time: {timestring}")

小提示:由于您明确需要 UTC(“Z”),我宁愿明确设置 timezone.utc 而不是使用 utcfromtimestamp(即 ...confusing)。