how to get modified date of the file in python

176 Views Asked by At

I have a file (it could be type of typing.IO or tempfile.SpooledTemproraryFile)

How I can get the date of the last modification, I don't know what is the path to the file, the only thing that I have is a file.

My code:

from tempfile import SpooledTemporaryFile
from typing import IO

def partition_csv( file: Union[IO, SpooledTemporaryFile] ):
#   read last modification time of file
2

There are 2 best solutions below

0
LoukasPap On

If file is of type SpooledTemporaryFile:

  1. To get the directory where the temporary files in your system are stored, use tempfile.gettempdir(): https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir.

  2. To get the last modification time: https://docs.python.org/3/library/os.path.html#os.path.getmtime.

import os
import tempfile

def partition_csv( file: Union[IO, SpooledTemporaryFile]):
    os.path.getmtime(tempfile.gettempdir() + file)
0
Abdelrahman Khallaf On

you can change file_name to the name of your file.

import os.path
import time

def get_modified_date(file_name):
    file_path=f"./{file_name}"
    # more info about os.path.getmtime function here: 
    # https://docs.python.org/3/library/os.path.html#os.path.getmtime
    modified_time = os.path.getmtime(file_path)
    return time.ctime(modified_time)

if __name__ == "__main__":
    file_name = "my_file.txt"
    modified_date = get_modified_date(file_name)
    print(modified_date)