iphone python批量修改照片创建日期

python批量修改照片创建日期
iphone根据文件名即可修改创建日期
其他手机可以根据文件名格式也可以实现
统一:根据读取拍摄信息修改创建日期

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):
    """
    经纬度转为小数, param arg:
    :return: 十进制小数
    """
    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值,这个可以注册一个百度开发者获得
    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

根据文件名修改文件的创建日期

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):
    """
    经纬度转为小数, param arg:
    :return: 十进制小数
    """
    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值,这个可以注册一个百度开发者获得
    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

代码参照的网上的,自己安装完包修改下路径就可以了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。