Last active
February 25, 2017 18:39
-
-
Save umeshnrao/825ac3091066a8ecb243e077860d3510 to your computer and use it in GitHub Desktop.
Change the modified time for all the files in a directory based on the timestamp present in the filename
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Script to change the last modified time of files | |
import os | |
import glob | |
import datetime | |
import time | |
from datetime import datetime | |
import re | |
# String to datetime object http://strftime.org/ | |
file_date = lambda x : x.split("_")[1].split(".")[0] | |
get_file_cre_dt = lambda x : datetime.strptime(x,'%Y-%m-%d-%H-%M-%S-%f') | |
'''for i,name in enumerate(glob.glob('/media/umesh/NOSTALGIA/ush/Screenshot*')): | |
stinfo = os.stat(name) | |
#print "{}: {} -- {} ".format(name,stinfo.st_atime,datetime.utcfromtimestamp(stinfo.st_atime)) | |
file_creation_ts = long(get_file_cre_dt(file_date(name)).strftime('%s')) | |
#print "{} {} {} ::: {} -- {} ".format(name.split("/")[-1], get_file_cre_dt(file_date(name)) , file_creation_ts , stinfo.st_mtime,datetime.utcfromtimestamp(stinfo.st_mtime)) | |
#os.utime(name,(file_creation_ts,file_creation_ts)) | |
''' | |
def folder_change_modif_time(folderpath,filename_pattern,get_date_from_filename,date_formatter): | |
for name in glob.glob( folderpath + filename_pattern ) : | |
filename = os.path.basename(name) | |
#file_creation_ts = long( date_formatter(get_date_from_filename(filename)).strftime('%s')) | |
try: | |
file_creation_ts = date_formatter(get_date_from_filename(filename)) | |
# Need to do this handle windows issue with strftime('%s') | |
file_ts_unix_fmt = long(time.mktime(file_creation_ts.timetuple())) | |
except Exception as ex: | |
print ex, name +" modification time can not modified as I can't get proper timestamp" | |
print filename,file_ts_unix_fmt | |
os.utime(name, (file_ts_unix_fmt,file_ts_unix_fmt)) | |
folder_change_modif_time('/media/umesh/NOSTALGIA/Screenshots/','Screenshot*',file_date,get_file_cre_dt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment