Python method of adding a timestamp to a filename

  • 2020-12-21 18:05:32
  • OfStack

Problem description:

1. (Add the timestamp first, then copy and move, both files plus the following file name are modified) Add the timestamp of the current moment to the 111.jpg file under the path of /home/kangle/webdata/JPEGImages

Rename it to something like 03-27-18-11-11_111.jpg and save it to another path /home/kangle/result


import datetime
nowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') #  now 
dir = "/home/kangle/webdata/JPEGImages"
for root, dirs, file in os.walk(dir):
 for b in file:
  if os.path.join(b).split('.')[1] == 'jpg':
   os.rename(dir + os.sep + b, dir + os.sep + str(nowTime) + '_' + b)
   print (dir, b)
   shutil.copy(os.path.join(dir, str(nowTime) + '_' + b), r'/home/kangle/result')

2, (when copying the mobile add file timestamp, the original folder file name the same below) will be/home kangle webdata/JPEGImages path under 111. jpg save file to another one under the path/home kangle/result, and add the current moment the timestamp of the renamed. Similar to 2018-03-27-2018-03-27 _111 jpg form


import datetime
nowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') #  now 
 
dir = "/home/kangle/webdata/JPEGImages"
for root, dirs, file in os.walk(dir):
 for b in file:
  if os.path.join(b).split('.')[1] == 'jpg':
   # os.rename(dir + os.sep + b, dir + os.sep + str(nowTime) + '_' + b)
   shutil.copy(os.path.join(dir, b),os.path.join("/home/kangle/result", str(nowTime) + '_' + b))
   # shutil.copy(os.path.join(dir, str(nowTime) + '_' + b), r'/home/kangle/result')

Related articles: