Code Examples

Get file modified date

programming

The following function, in Python, creates a file in current directory and returns its last modification date and time.

import os
import datetime

# =============================================================================
# The following function creates a file in current directory
# and returns its last modification date and time
# =============================================================================

def file_date(filename):
  
  # Create the file in the current directory
  # if file alredy exists, open it in write mode
  f = open(filename,"w")
  
  # get timestamp of last modification
  timestamp = os.path.getmtime(filename)
  
  # Convert the timestamp into a readable format, then into a string
  strdate = datetime.datetime.fromtimestamp(
            timestamp).strftime("%Y-%m-%d %H:%M:%S")
  
  # close the file
  f.close()
  
  # Return modified date and time
  return ("{0}".format(strdate))

print(file_date("newfile.txt")) 
# Should be today's date in the format of yyyy-mm-dd H:M:S