0%

Python修改文件时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import time
from datetime import datetime
from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle
from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING
from pywintypes import Time #忽略此处报错,不影响运行


def modifyFileTime(filePath, createTime, modifyTime, accessTime, offset):
"""
用来修改任意文件的相关时间属性,时间格式:YYYY-MM-DD HH:MM:SS 例如:2019-02-02 00:01:02
:param filePath: 文件路径名
:param createTime: 创建时间
:param modifyTime: 修改时间
:param accessTime: 访问时间
:param offset: 时间偏移的秒数,tuple格式,顺序和参数时间对应
"""
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)


def timeOffsetAndStruct(times, format, offset):
return time.localtime(time.mktime(time.strptime(times, format)) + offset)


offset = (0, 1, 2)
for root, dirs, files in os.walk('F:\\Blog\\source\\_posts'):
for file in files:
filepath = root + '\\' + file
"""
用来获取任意文件的相关时间属性
"""
ctime = str(datetime.fromtimestamp(os.path.getctime(filepath)))[:19]
mtime = str(datetime.fromtimestamp(os.path.getmtime(filepath)))[:19]
atime = str(datetime.fromtimestamp(os.path.getatime(filepath)))[:19]

modifyFileTime(filepath, ctime, mtime, atime, offset)

赏点呗!