iphone python批量修改照片創(chuàng)建日期

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

代碼參照的網上的米愿,自己安裝完包修改下路徑就可以了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末威始,一起剝皮案震驚了整個濱河市致扯,隨后出現(xiàn)的幾起案子肤寝,更是在濱河造成了極大的恐慌,老刑警劉巖抖僵,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鲤看,死亡現(xiàn)場離奇詭異,居然都是意外死亡耍群,警方通過查閱死者的電腦和手機义桂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蹈垢,“玉大人慷吊,你說我怎么就攤上這事〔芴В” “怎么了溉瓶?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長谤民。 經常有香客問我堰酿,道長,這世上最難降的妖魔是什么张足? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任触创,我火速辦了婚禮,結果婚禮上兢榨,老公的妹妹穿的比我還像新娘嗅榕。我一直安慰自己,他們只是感情好吵聪,可當我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布凌那。 她就那樣靜靜地躺著,像睡著了一般吟逝。 火紅的嫁衣襯著肌膚如雪帽蝶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天块攒,我揣著相機與錄音励稳,去河邊找鬼。 笑死囱井,一個胖子當著我的面吹牛驹尼,可吹牛的內容都是我干的。 我是一名探鬼主播庞呕,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼新翎,長吁一口氣:“原來是場噩夢啊……” “哼程帕!你這毒婦竟也來了?” 一聲冷哼從身側響起地啰,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤愁拭,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后亏吝,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體岭埠,經...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年蔚鸥,在試婚紗的時候發(fā)現(xiàn)自己被綠了惜论。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡株茶,死狀恐怖来涨,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情启盛,我是刑警寧澤,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布技羔,位于F島的核電站僵闯,受9級特大地震影響,放射性物質發(fā)生泄漏藤滥。R本人自食惡果不足惜鳖粟,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望拙绊。 院中可真熱鬧向图,春花似錦、人聲如沸标沪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽金句。三九已至檩赢,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間违寞,已是汗流浹背贞瞒。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留趁曼,地道東北人军浆。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像挡闰,于是被迫代替她去往敵國和親乒融。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,955評論 2 355