A script to set file timestamps based on filenames

I’ve noticed that SyncThing didn’t seem to preserve modification timestamps for the photos and videos transferred from my phone. Since this messed up sorting by date, and the timestamps are present in filenames, I’ve made a trivial script to set mtimes appropriately.

Note that it assumes that the filenames have local time for Poland.

#!/usr/bin/env python

import datetime
import os
import re
import zoneinfo

# e.g. IMG_yyyymmdd_hhmmss...
NAME_REGEX = re.compile(r"\w+_(\d\d\d\d)(\d\d)(\d\d)_(\d\d)(\d\d)(\d\d)")

for f in os.listdir("."):
    if m := NAME_REGEX.match(f):
        dt = datetime.datetime(*[int(g, 10) for g in m.groups()],
        os.utime(f, (dt.timestamp(), dt.timestamp()))

Leave a Reply

Your email address will not be published.