python批量修改照片創(chuàng)建日期
iphone根據文件名即可修改創(chuàng)建日期
其他手機可以根據文件名格式也可以實現(xiàn)
統(tǒng)一:根據讀取拍攝信息修改創(chuàng)建日期
1 根據拍攝信息修改文件名
from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle
from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING
from pywintypes import Time
import time
import os, re
import re
import json
import requests
import exifread
def modifyFileTime(filepath, createTime, modifyTime, accessTime,offset):
"""
用來修改任意文件的相關時間屬性,時間格式:20190202000102
"""
try:
format = "%Y%m%d%H%M%S" #時間格式
cTime_t = timeOffsetAndStruct(createTime,format,offset[0])
mTime_t = timeOffsetAndStruct(modifyTime,format,offset[1])
aTime_t = timeOffsetAndStruct(accessTime,format,offset[2])
fh = CreateFile(filepath, GENERIC_READ | GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, 0)
createTimes, accessTimes, modifyTimes = GetFileTime(fh)
createTimes = Time(time.mktime(cTime_t))
accessTimes = Time(time.mktime(aTime_t))
modifyTimes = Time(time.mktime(mTime_t))
SetFileTime(fh, createTimes, accessTimes, modifyTimes)
CloseHandle(fh)
return 0
except:
return 1
#結構化時間
def timeOffsetAndStruct(times, format, offset):
return time.localtime(time.mktime(time.strptime(times, format)) + offset)
# 將文件名中的空格修改為橫杠
def space2bar(dirname, basename):
newname = basename.replace(' ', '-')
os.rename(os.path.join(dirname, basename), os.path.join(dirname, newname))
return newname
# 獲取文件名中的時間用于修改
def get_time(basename):
temp_str = basename.split('-')
# 獲取temp_str[4]的前6位作為時分秒
h_m_s = temp_str[3][0:6]
temp_time = temp_str[0]+temp_str[1]+temp_str[2]+h_m_s
return temp_time
# 讀取照片的GPS經緯度信息
def find_GPS_image(pic_path):
GPS = {}
date = ''
with open(pic_path, 'rb') as f:
tags = exifread.process_file(f)
for tag, value in tags.items():
# 緯度
if re.match('GPS GPSLatitudeRef', tag):
GPS['GPSLatitudeRef'] = str(value)
# 經度
elif re.match('GPS GPSLongitudeRef', tag):
GPS['GPSLongitudeRef'] = str(value)
# 海拔
elif re.match('GPS GPSAltitudeRef', tag):
GPS['GPSAltitudeRef'] = str(value)
elif re.match('GPS GPSLatitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLatitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSLongitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLongitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSAltitude', tag):
GPS['GPSAltitude'] = str(value)
elif re.match('.*Date.*', tag):
date = str(value)
return {'GPS_information': GPS, 'date_information': date}
# 轉換經緯度格式
def latitude_and_longitude_convert_to_decimal_system(*arg):
"""
經緯度轉為小數(shù), param arg:
:return: 十進制小數(shù)
"""
return float(arg[0]) + ((float(arg[1]) + (float(arg[2].split('/')[0]) / float(arg[2].split('/')[-1]) / 60)) / 60)
# 通過baidu Map的API將GPS信息轉換成地址
def find_address_from_GPS(GPS):
"""
使用Geocoding API把經緯度坐標轉換為結構化地址屯碴。
:param GPS:
:return:
"""
# 調用百度API的ak值蝶溶,這個可以注冊一個百度開發(fā)者獲得
secret_key = 'zbLsuDDL4CS2U0M4KezOZZbGUY9iWtVf'
if not GPS['GPS_information']:
return '該照片無GPS信息'
lat, lng = GPS['GPS_information']['GPSLatitude'], GPS['GPS_information']['GPSLongitude']
baidu_map_api = "http://api.map.baidu.com/geocoder/v2/?ak={0}&callback=renderReverse&location={1},{2}s&output=json&pois=0".format(secret_key, lat, lng)
response = requests.get(baidu_map_api)
content = response.text.replace("renderReverse&&renderReverse(", "")[:-1]
print(content)
baidu_map_address = json.loads(content)
formatted_address = baidu_map_address["result"]["formatted_address"]
province = baidu_map_address["result"]["addressComponent"]["province"]
city = baidu_map_address["result"]["addressComponent"]["city"]
district = baidu_map_address["result"]["addressComponent"]["district"]
location = baidu_map_address["result"]["sematic_description"]
return formatted_address, province, city, district, location
if __name__ == '__main__':
expression = r"\d{4}-\d{2}-\d{2}-\d{6}" # 文件名格式
dirname = r'D:\BaiduNetdiskDownload\imgbackup - 副本'
offset = (0,1,2)
basenames = os.listdir(dirname)
print(basenames)
for basename in basenames:
if basename:
filepath = dirname+'\\'+basename
# todo獲取照片的拍攝時間
path = filepath
try:
GPS_info = find_GPS_image(pic_path=path)
address = find_address_from_GPS(GPS=GPS_info)
print("拍攝時間:" + GPS_info.get("date_information"))
print('照片拍攝地址:' + str(address))
cTime=mTime=aTime=GPS_info.get("date_information").replace(":", "").replace(" ", "")
print(filepath, cTime)
r = modifyFileTime(filepath, cTime, mTime, aTime, offset)
# 修改文件名
qian = dirname+r'\\'
houzhui = filepath.split('.')[-1]
new_name = qian+cTime[0:4]+'-'+cTime[4:6]+'-'+cTime[6:8]+'-'+cTime[8:]+'.'+houzhui
print(filepath, new_name)
os.rename(filepath, new_name)
if r == 0:
print(basename+'>>>>'+'修改完成')
elif r == 1:
print(basename+'>>>>'+'修改失敗')
except:
print(filepath,'修改失敗')
2
根據文件名修改文件的創(chuàng)建日期
from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle
from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING
from pywintypes import Time
import time
import os, re
import re
import json
import requests
import exifread
def modifyFileTime(filepath, createTime, modifyTime, accessTime,offset):
"""
用來修改任意文件的相關時間屬性馁蒂,時間格式:20190202000102
"""
try:
format = "%Y%m%d%H%M%S" #時間格式
cTime_t = timeOffsetAndStruct(createTime,format,offset[0])
mTime_t = timeOffsetAndStruct(modifyTime,format,offset[1])
aTime_t = timeOffsetAndStruct(accessTime,format,offset[2])
fh = CreateFile(filepath, GENERIC_READ | GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, 0)
createTimes, accessTimes, modifyTimes = GetFileTime(fh)
createTimes = Time(time.mktime(cTime_t))
accessTimes = Time(time.mktime(aTime_t))
modifyTimes = Time(time.mktime(mTime_t))
SetFileTime(fh, createTimes, accessTimes, modifyTimes)
CloseHandle(fh)
return 0
except:
return 1
#結構化時間
def timeOffsetAndStruct(times, format, offset):
return time.localtime(time.mktime(time.strptime(times, format)) + offset)
# 將文件名中的空格修改為橫杠
def space2bar(dirname, basename):
newname = basename.replace(' ', '-')
os.rename(os.path.join(dirname, basename), os.path.join(dirname, newname))
return newname
# 獲取文件名中的時間用于修改
def get_time(basename):
temp_str = basename.split('-')
# 獲取temp_str[4]的前6位作為時分秒
h_m_s = temp_str[3][0:6]
temp_time = temp_str[0]+temp_str[1]+temp_str[2]+h_m_s
return temp_time
# 讀取照片的GPS經緯度信息
def find_GPS_image(pic_path):
GPS = {}
date = ''
with open(pic_path, 'rb') as f:
tags = exifread.process_file(f)
for tag, value in tags.items():
# 緯度
if re.match('GPS GPSLatitudeRef', tag):
GPS['GPSLatitudeRef'] = str(value)
# 經度
elif re.match('GPS GPSLongitudeRef', tag):
GPS['GPSLongitudeRef'] = str(value)
# 海拔
elif re.match('GPS GPSAltitudeRef', tag):
GPS['GPSAltitudeRef'] = str(value)
elif re.match('GPS GPSLatitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLatitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSLongitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLongitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSAltitude', tag):
GPS['GPSAltitude'] = str(value)
elif re.match('.*Date.*', tag):
date = str(value)
return {'GPS_information': GPS, 'date_information': date}
# 轉換經緯度格式
def latitude_and_longitude_convert_to_decimal_system(*arg):
"""
經緯度轉為小數(shù), param arg:
:return: 十進制小數(shù)
"""
return float(arg[0]) + ((float(arg[1]) + (float(arg[2].split('/')[0]) / float(arg[2].split('/')[-1]) / 60)) / 60)
# 通過baidu Map的API將GPS信息轉換成地址
def find_address_from_GPS(GPS):
"""
使用Geocoding API把經緯度坐標轉換為結構化地址辆床。
:param GPS:
:return:
"""
# 調用百度API的ak值,這個可以注冊一個百度開發(fā)者獲得
secret_key = 'zbLsuDDL4CS2U0M4KezOZZbGUY9iWtVf'
if not GPS['GPS_information']:
return '該照片無GPS信息'
lat, lng = GPS['GPS_information']['GPSLatitude'], GPS['GPS_information']['GPSLongitude']
baidu_map_api = "http://api.map.baidu.com/geocoder/v2/?ak={0}&callback=renderReverse&location={1},{2}s&output=json&pois=0".format(secret_key, lat, lng)
response = requests.get(baidu_map_api)
content = response.text.replace("renderReverse&&renderReverse(", "")[:-1]
print(content)
baidu_map_address = json.loads(content)
formatted_address = baidu_map_address["result"]["formatted_address"]
province = baidu_map_address["result"]["addressComponent"]["province"]
city = baidu_map_address["result"]["addressComponent"]["city"]
district = baidu_map_address["result"]["addressComponent"]["district"]
location = baidu_map_address["result"]["sematic_description"]
return formatted_address, province, city, district, location
if __name__ == '__main__':
expression = r"\d{4}-\d{2}-\d{2}-\d{6}" # 文件名格式
dirname = r'D:\BaiduNetdiskDownload\imgbackup - 副本'
offset = (0,1,2)
basenames = os.listdir(dirname)
for basename in basenames:
# 去掉文件名中的空格
if len(basename.split(' ')) > 1:
basename = space2bar(dirname, basename)
if re.match(expression, basename):
filepath = dirname+'\\'+basename
# 獲取文件名中的時間
temp_time = get_time(basename)
# # todo 獲取照片的拍攝時間
# path = r'D:\Users\Administrator\Desktop\圖片.jpg' # 圖片存放路徑
# GPS_info = find_GPS_image(pic_path=path)
# address = find_address_from_GPS(GPS=GPS_info)
# print("拍攝時間:" + GPS_info.get("date_information"))
# print('照片拍攝地址:' + str(address))
cTime=mTime=aTime=temp_time
print(filepath, cTime)
r = modifyFileTime(filepath, cTime, mTime, aTime,offset)
if r == 0:
print(basename+'>>>>'+'修改完成')
elif r == 1:
print(basename+'>>>>'+'修改失敗')
else:
print(basename+'>>>>'+'文件名格式不符合')
break
代碼參照的網上的米愿,自己安裝完包修改下路徑就可以了