def get_date_taken(file_path: Path) -> datetime: try: with open(str(file_path), 'rb') as file: my_image = Image(file) if my_image.has_exif: date_time = my_image.get('datetime_original') if date_time is not None: return pendulum.from_format(date_time, "YYYY:MM:DD HH:mm:ss") except AssertionError: properties = propsys.SHGetPropertyStoreFromParsingName(str(file_path)) dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() if dt is None: dt = properties.GetValue(pscon.PKEY_Media_DateReleased).GetValue() if dt is None: dt = properties.GetValue(pscon.PKEY_Photo_DateTaken).GetValue() if dt is None: dt = properties.GetValue( pscon.PKEY_RecordedTV_OriginalBroadcastDate).GetValue() if dt is not None: return pendulum.instance(dt) return None
def get_music_file_info(path): ''' Using win32com, this function gets path to a file and based on PKEY values, according to https://docs.microsoft.com/en-us/windows/win32/, returns a dictionary of path, name, artist and length [min] of a song ''' try: properties = propsys.SHGetPropertyStoreFromParsingName(path) except Exception as exception: print("Something went wrong.") print(exception) return None else: artist = properties.GetValue(pscon.PKEY_Music_Artist).GetValue()[0] name = properties.GetValue(pscon.PKEY_Title).GetValue() length = properties.GetValue(pscon.PKEY_Media_Duration).GetValue( ) #returns duration in 100ns units length_minutes = length * 100 / (pow(10, 9) * 60) #multiplying by 100 to get length in ns unit, then dividing by 10^9 to get seconds #and then dividing again by 60 to get minutes return { 'path': path, 'name': name, 'artist': artist, 'length': length_minutes }
def get_date_time(meta_data_source, source_path, xmp_meta): date_times = [] xmp_date_time = get_xmp_date_time(xmp_meta) if xmp_date_time: date_times.append(xmp_date_time) date_times += get_exif_date_times(meta_data_source) properties = propsys.SHGetPropertyStoreFromParsingName(source_path) dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() if dt: date_times.append(dt) else: dt = properties.GetValue(pscon.PKEY_DateModified).GetValue() if dt: date_times.append(dt) if len(date_times) == 0: logger.warning('No Date time!') return None oldest_date_time = date_times[0].replace(tzinfo=None) for date_time in date_times: date_time = date_time.replace(tzinfo=None) oldest_date_time = oldest_date_time if oldest_date_time < date_time else date_time return oldest_date_time
def PrintShortcutProperties(shortcut_path, dump_all): properties = propsys.SHGetPropertyStoreFromParsingName(shortcut_path) print 'Known properties (--dump-all for more):' app_id = properties.GetValue(pscon.PKEY_AppUserModel_ID).GetValue() print '\tAppUserModelId => "%s"' % app_id # Hard code PKEY_AppUserModel_IsDualMode as pscon doesn't support it. PKEY_AppUserModel_IsDualMode = (IID('{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'), 11) dual_mode = properties.GetValue(PKEY_AppUserModel_IsDualMode).GetValue() print '\tDual Mode => "%s"' % dual_mode # Dump all other properties with their raw ID if requested, add them above # over time as we explicitly care about more properties, see propkey.h or # pscon.py for a reference of existing PKEYs' meaning. if dump_all: key_to_name = BuildPKeyToNameMapping() print '\nOther properties:' for i in range(0, properties.GetCount()): property_key = properties.GetAt(i) # |property_key| is a tuple of an IID identifying the format and an int # (a.k.a. a PROPERTYKEY struct). If this key is one of the predefined ones # in the pscon module, display the name given to it by the module. If not, # show the key's IID and int -- the viewer may be able to find it in # propkey.h. key_name = key_to_name.get(property_key, str(property_key)) property_value = properties.GetValue(property_key).GetValue() print '\t%s => "%s"' % (key_name, property_value)
def get_windows_sys_props(self, filename): print("WIN32COM.PROPSYS FILE PROPERTIES: ") pk = propsys.PSGetPropertyKeyFromName("System.Keywords") # get property store for a given shell item (here a file) # MAKE SURE YOU USE THE RIGHT SLASHES HERE: ps = propsys.SHGetPropertyStoreFromParsingName( filename.replace('/', '\\')) # build an array of string type PROPVARIANT # newValue = propsys.PROPVARIANTType(["hello", "world"], pythoncom.VT_VECTOR | pythoncom.VT_BSTR) # # write property # ps.SetValue(pk, newValue) # ps.Commit() # read & print existing (or not) property value, System.Keywords type is an array of string title = ps.GetValue(pscon.PKEY_Title).GetValue() print(title) print( "System.Audio.Format", ps.GetValue(propsys.PSGetPropertyKeyFromName( "System.Audio.Format")).GetValue()) # keywords = ps.GetValue(pk).GetValue() # print(keywords) for keyname in keysToGet: print( "{}: ".format(keyname), ps.GetValue( propsys.PSGetPropertyKeyFromName(keyname)).GetValue())
def make_shortcut(appname): """Create a shortcut file in the labscript suite install dir for the given app""" shortcut_path = os.path.join(labscript_installation, launcher_name(appname)) app_dir = os.path.join(labscript_installation, appname) _check_windows() shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortcut(shortcut_path) target, args = launch_command(appname) shortcut.TargetPath = target shortcut.Arguments = args shortcut.WorkingDirectory = '"%s"' % app_dir shortcut.IconLocation = os.path.join(app_dir, appname + '.ico') shortcut.Description = app_descriptions[appname] shortcut.save() store = propsys.SHGetPropertyStoreFromParsingName( shortcut_path, None, shellcon.GPS_READWRITE, propsys.IID_IPropertyStore) store.SetValue( pscon.PKEY_AppUserModel_ID, propsys.PROPVARIANTType(str(appids[appname]), pythoncom.VT_LPWSTR), ) store.Commit() return shortcut_path
def tunnusega_failid(kaust, tunnus): jarjend = [] for i in os.walk(kaust): for j in i[2]: fail_dir = kaust + aa[0] + j properties = propsys.SHGetPropertyStoreFromParsingName(fail_dir) title = properties.GetValue(votmed[tunnus]) try: liide = tunnuse_saamine(title, tunnus) except TypeError or NameError: continue if title.GetValue() is not None: jarjend.append([j, liide]) return jarjend
def sorteeri_tunnus(kaust, tunnus): for l in os.walk(kaust): for m in l[2]: fail_dir = kaust + aa[0] + m properties = propsys.SHGetPropertyStoreFromParsingName(fail_dir) title = properties.GetValue(votmed[tunnus]) try: liide = tunnuse_saamine(title, tunnus) uus_dir = kaust + aa[0] + liide if not os.path.isdir(uus_dir): os.mkdir(uus_dir) shutil.copy(fail_dir, uus_dir) except TypeError or NameError: print("Faili " + fail_dir + " žanri ei õnnestunud leida") main_base.destroy()
def make_shortcut(path, target, arguments, working_directory, icon_path, description, appid): _check_windows() shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortcut(path) shortcut.TargetPath = target shortcut.Arguments = arguments shortcut.WorkingDirectory = working_directory shortcut.IconLocation = icon_path shortcut.Description = description shortcut.save() store = propsys.SHGetPropertyStoreFromParsingName( path, None, shellcon.GPS_READWRITE, propsys.IID_IPropertyStore) store.SetValue( pscon.PKEY_AppUserModel_ID, propsys.PROPVARIANTType(str(appid), pythoncom.VT_LPWSTR), ) store.Commit()
def getMediaDate(file): try: properties = propsys.SHGetPropertyStoreFromParsingName(file) dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() if dt is None: return None if not isinstance(dt, datetime): dt = datetime.fromtimestamp(int(dt)) dt = dt.replace(tzinfo=pytz.timezone('UTC')) dt_bucharest = dt.astimezone(pytz.timezone('Europe/Bucharest')) dt_bucharest = dt_bucharest.replace(tzinfo=None) epoch = datetime.utcfromtimestamp(0) fileTime = (dt_bucharest - epoch).total_seconds() + 2*60*60 if fileTime < 946684800: return None return fileTime except: #print("ERROR when get mediaDate from: " + file) return None
def getMovieProperties(filepath: str): dt = datetime.datetime.now() try: properties = propsys.SHGetPropertyStoreFromParsingName(filepath) dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() if not isinstance(dt, datetime.datetime): if not isinstance(dt, type(None)): dt = datetime.datetime.fromtimestamp(int(dt)) dt = dt.replace(tzinfo=pytz.timezone('UTC')) except Exception as e: p(warning, 'File', filepath, 'could not be poked for date creation', e) pass if dt == None: dt = getDateFromFilename(filepath) return dt
def PrintShortcutProperties(shortcut_path, dump_all): properties = propsys.SHGetPropertyStoreFromParsingName(shortcut_path) print 'Known properties (--dump-all for more):' app_id = properties.GetValue(pscon.PKEY_AppUserModel_ID).GetValue() print '\tAppUserModelId => "%s"' % app_id # Hard code PKEY_AppUserModel_IsDualMode as pscon doesn't support it. PKEY_AppUserModel_IsDualMode = ( IID('{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}'), 11) dual_mode = properties.GetValue(PKEY_AppUserModel_IsDualMode).GetValue() print '\tDual Mode => "%s"' % dual_mode # Dump all other properties with their raw ID if requested, add them above # over time as we explicitly care about more properties, see propkey.h or # pscon.py for a reference of existing PKEYs' meaning. if dump_all: print '\nOther properties:' for i in range(0, properties.GetCount()): property_key = properties.GetAt(i) property_value = properties.GetValue(property_key).GetValue() print '\t%s => "%s"' % (property_key, property_value)
def create_shortcut( shortcut_path, target, arguments=(), working_directory=None, icon_file=None, display_name=None, appusermodel_id=None, ): """Create a Windows shortcut at the given path, which should be a filepath ending in '.lnk'. Arguments should be a list or tuple of arguments - not a single string of arguments separated by spaces.""" shortcut_path = Path(shortcut_path) shortcut_path.parent.mkdir(parents=True, exist_ok=True) _checkwindows() objShell = Dispatch('WScript.Shell') shortcut = objShell.CreateShortcut(str(shortcut_path)) shortcut.TargetPath = str(target) if arguments: shortcut.Arguments = list2cmdline(arguments) if working_directory is not None: shortcut.WorkingDirectory = str(working_directory) if icon_file is not None: shortcut.IconLocation = str(icon_file) if display_name is not None: shortcut.Description = display_name shortcut.save() if appusermodel_id is not None: # Edit the shortcut to associate the AppUserModel_ID with it: store = propsys.SHGetPropertyStoreFromParsingName( str(shortcut_path), None, shellcon.GPS_READWRITE, propsys.IID_IPropertyStore) store.SetValue(pscon.PKEY_AppUserModel_ID, propsys.PROPVARIANTType(appusermodel_id)) store.Commit()
import os import time from moviepy.editor import VideoFileClip import pytz import datetime import exifread from win32com.propsys import propsys, pscon import pythoncom import shutil m = 0 f = open('tmp.csv', 'w', encoding='utf8') for root, dir, file in os.walk('download'): for n in file: m = m + 1 path1 = os.path.abspath(os.path.join(root, n)) properties = propsys.SHGetPropertyStoreFromParsingName(path1) dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() dt = dt.replace(tzinfo=pytz.timezone('UTC')) name = dt.strftime('%Y-%m-%d') old_path = os.path.join(root, n) new_path1 = os.path.join(root, str(name) + n) list1 = [old_path, new_path1] f.write(','.join(list1) + '\n') f.close()
y = int(source_file[prefix_end:prefix_end + 4]) m = int(source_file[prefix_end + 4:prefix_end + 6]) d = int(source_file[prefix_end + 6:prefix_end + 8]) elif (source_file[:4].upper() == "MOV_"): # Videos from Xpedia Z5; can use the Windows file last modified date... # UPDATE No we can't! Need to redo this section (and work out which "MOV_*" files this works for) TODO if (logging == 1): print("SCENARIO: filename == MOV_") # dtstring = os.path.getmtime(source_dir + source_file) <-- the old method, but wasn't working for files from Sony Xpedia. # print(str(dt)) # y = int(time.strftime('%Y', time.gmtime(dtstring))) # m = int(time.strftime('%m', time.gmtime(dtstring))) # d = int(time.strftime('%d', time.gmtime(dtstring))) properties = propsys.SHGetPropertyStoreFromParsingName(source_dir + source_file) dtstring = str( properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()) y = int(dtstring[0:4]) m = int(dtstring[5:7]) d = int(dtstring[8:10]) if (logging == 1): print("y/m/d = " + str(y) + "/" + str(m) + "/" + str(d)) elif (extension == "JPG" or extension == "JPEG"): # it's from another source (eg, my old Panasonic Lumix camera) # For images, pull date from EXIF # For video, pull "Date acquired" directly from the binary if (logging == 1): print("SCENARIO: ext == [JPG|JPEG]") # ctime and mtime aren't what I need - I need Windows "Date acquired", or (better still?) pull information from image or video exif
img_folder = "E:\\微云照片备份\\" new_folder = "E:\\WeiYunBackup\\" if __name__ == '__main__': g = os.walk(img_folder) for path, d, file_list in g: for file_name in file_list: full_file_name = os.path.join(path, file_name) new_full_file_name = full_file_name file_suffix = os.path.splitext(file_name)[-1] new_name = "" if file_suffix.lower() in ['.mp4', '.mov', '.avi', ".jpg", ".png"]: if file_suffix.lower() in ['.mp4', '.mov', '.avi']: # 如果是视频,使用媒体创建日期 properties = propsys.SHGetPropertyStoreFromParsingName( full_file_name) dt = properties.GetValue( pscon.PKEY_Media_DateEncoded).GetValue() properties = None # release file handle if dt: if not isinstance(dt, datetime.datetime): # In Python 2, PyWin32 returns a custom time type instead of # using a datetime subclass. It has a Format method for strftime # style formatting, but let's just convert it to datetime: dt = datetime.datetime.fromtimestamp(int(dt)) dt = dt.replace(tzinfo=pytz.timezone('UTC')) dt_shanghai = dt.astimezone( pytz.timezone('Asia/Shanghai')) new_name = dt_shanghai.strftime('%Y%m%d_%H%M%S') else: tags = getExif(full_file_name)
# os.rename("61bef91f8d51eea10edac514cccfeaa0.mp4","2016_06_04_14_36_37_61bef91f8d51eea10edac514cccfeaa0.mp4") import os import datetime import dateutil.parser import shutil from win32com.propsys import propsys, pscon if __name__ == "__main__": PATH = "." for filename in os.listdir(PATH): # try: properties = propsys.SHGetPropertyStoreFromParsingName( os.getcwd() + "\\" + filename ) dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() if dt: newName = ( ( dateutil.parser.parse(str(dt)) + datetime.timedelta(hours=8) ).strftime("%Y_%m_%d_%H_%M_%S") + "_" + filename ) #newName = "123.mp4" # print(newName) print("os.rename(\""+filename + "\",\"" + newName+"\")")