Quantcast
Channel: Michał Górny
Viewing all articles
Browse latest Browse all 60

A script to set file timestamps based on filenames

$
0
0

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()],
                               tzinfo=zoneinfo.ZoneInfo("Poland"))
        os.utime(f, (dt.timestamp(), dt.timestamp()))

Viewing all articles
Browse latest Browse all 60

Trending Articles