Ubuntu – How to change the filename timestamp

command linefilenametimestamp

I have dat files' names in chronological order:

FileName_YYYY_MM_DD_HHMM.dat

Is there any commands for adding 30 minutes to each timestamp?

Best Answer

Using python :

#!/usr/bin/env python2
import glob, re, os, datetime
os.chdir('/path/to/dir')
for f in glob.glob('*.dat'):
    ini_time = datetime.datetime.strptime(re.search(r'(?<=_)(?:\d|_)+(?=.dat$)', f).group(), '%Y_%m_%d_%H%M')
    fin_time = (ini_time + datetime.timedelta(minutes=30)).strftime('%Y_%m_%d_%H%M%S')
    os.rename(f, 'Filename_' + str(fin_time) + '.dat')
  • os.chdir('/path/to/dir') will change the current directory to the directory containing the .dat files. Replace /path/to/dir with the actual path.

  • glob.glob('*.dat') will find the files ending in .dat

  • ini_time variable will at first cut out the date-time from the original file name using re module and then sort out which entry represents what in the string that is taken out so that we can add the required time to this

  • fin_time will contain the resultant time i.e. ini_time plus 30 minutes

  • os.rename will rename the file accordingly.

Also note that, with successive file names (differed by 30 minutes) the renamed file will overwrite the next one, hence it it is better to add the seconds to the renamed file name so that it remains safe. Otherwise you need to save the renamed files to a different directory and then replace them with the original ones later.