Open In App

Python Script to change name of a file to its timestamp

A Digital Timestamp is a sequence of characters(usually a combination of digits and delimiters), identifying the time when a certain event occurred. In computer science, timestamps are generally used for marking the time of the creation of a virtual entity but are not limited to this in its use case. Digital Timestamps are implemented in various standards, each favoring a particular use case. i.e. some standards make use of less precise timestamps (only storing date of event), some standards encode the timezone information in the timestamp. But the base syntax of timestamp remains largely the same between standards, which prevents alienation and provides flexibility in choosing one. 

In this article, we will learn how to obtain the date of creation of a file and would use that to create an ISO 8601 timestamp. Which would be used to name the file.



Functions Used:

File before Rename:






import time
import os
 
 
# Getting the path of the file
f_path = "/location/to/gfg.png"
 
# Obtaining the creation time (in seconds)
# of the file/folder (datatype=int)
t = os.path.getctime(f_path)
 
# Converting the time to an epoch string
# (the output timestamp string would
# be recognizable by strptime() without
# format quantifiers)
t_str = time.ctime(t)
 
# Converting the string to a time object
t_obj = time.strptime(t_str)
 
# Transforming the time object to a timestamp
# of ISO 8601 format
form_t = time.strftime("%Y-%m-%d %H:%M:%S", t_obj)
 
# Since colon is an invalid character for a
# Windows file name Replacing colon with a
# similar looking symbol found in unicode
# Modified Letter Colon " " (U+A789)
form_t = form_t.replace(":", "꞉")
 
# Renaming the filename to its timestamp
os.rename(
    f_path, os.path.split(f_path)[0] + '/' + form_t + os.path.splitext(f_path)[1])

File after Rename:

Things to keep in mind while using the above code:


Article Tags :