Search code examples
pythonpython-3.xdatetimeunix-timestamp

Outputting timestamps from a list of files


I'm having problems outputting timestamps for files in a directory. Want to list timestamps if they reach a certain time window, currently can't even get output. Not sure what I am doing wrong and hitting a wall 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()

The following snippet works, but is obviously not much of a program

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)

Solution

  • The main issue was the module name. You need to check for __main__, not main. You also were not passing any parameter to the convert_timestamps function.

    This code should work:

    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()
    

    Output

    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