Python Script to change name of a file to its timestamp

Python Script to change name of a file to its timestamp

To rename a file to its timestamp, you'll first need to get the file's creation or modification timestamp. Then, you can use that timestamp to rename the file. Here's how you can do it using Python:

  1. Use the os module to get the file's timestamp.
  2. Use the datetime module to convert the timestamp to a readable string format.
  3. Rename the file with the generated timestamp string.

Here's a script that demonstrates this:

import os import datetime def rename_file_to_timestamp(file_path): # Get the file's modification time timestamp = os.path.getmtime(file_path) # Convert timestamp to a datetime object dt_object = datetime.datetime.fromtimestamp(timestamp) # Convert the datetime object to a string format formatted_time = dt_object.strftime('%Y%m%d_%H%M%S') # Generate the new file name file_extension = os.path.splitext(file_path)[1] new_file_name = formatted_time + file_extension # Generate the new file path directory = os.path.dirname(file_path) new_file_path = os.path.join(directory, new_file_name) # Rename the file os.rename(file_path, new_file_path) print(f"File renamed to: {new_file_name}") # Example usage file_path = "/path/to/your/file.ext" rename_file_to_timestamp(file_path) 

Replace /path/to/your/file.ext with the path to your file. The script will rename the file to its modification timestamp in the format YYYYMMDD_HHMMSS.ext.

If you wish to rename based on the file's creation timestamp instead, replace os.path.getmtime(file_path) with os.path.getctime(file_path).


More Tags

mailto kaggle installation listview children google-calendar-api phantomjs iphone asynchronous spring-cloud

More Programming Guides

Other Guides

More Programming Examples