Update Markdown file creation dates
As I’ve migrated files between different apps over the years, in many cases the act of exporting or recreating notes has created inconsistency between the actual creation date (metadata in Finder) and the date metadata added to the top of the file in YAML front matter.
This is a simple utility that takes a directory, finds Markdown files, checks front matter for either date: YYYY-MM-DD or date: MM-DD-YYYY, and updates the file’s creation date using the macOS SetFile command. The date has to be in YAML front matter at the very top of the file, between the opening and closing --- lines, and can be quoted or unquoted. A date: line further down in the body is ignored.
Prerequisites
This script runs on macOS and needs Python 3 and Apple’s Command Line Tools, which provide SetFile. It isn’t part of macOS itself, so if you don’t already have Xcode or the Command Line Tools, install them with:
xcode-select --install
Apple has marked SetFile as deprecated, so a future version of the Command Line Tools may drop it.
Script
import os
import re
import shutil
import subprocess
import sys
from datetime import datetime
DATE_PATTERN = re.compile(r"""^date:\s*["']?(\d{4}-\d{2}-\d{2}|\d{2}-\d{2}-\d{4})""")
def find_front_matter_date(file_path):
"""Return the date string from YAML front matter, or None."""
with open(file_path, encoding="utf-8-sig") as f:
if f.readline().strip() != "---":
return None
for line in f:
if line.strip() == "---":
return None
match = DATE_PATTERN.match(line)
if match:
return match.group(1)
return None
def parse_date(date_str):
fmt = "%Y-%m-%d" if len(date_str.split("-")[0]) == 4 else "%m-%d-%Y"
return datetime.strptime(date_str, fmt)
def update_file_dates(directory):
updated = 0
for root, _dirs, files in os.walk(directory):
for file in files:
if not file.endswith(".md"):
continue
file_path = os.path.join(root, file)
try:
date_str = find_front_matter_date(file_path)
if not date_str:
continue
formatted = parse_date(date_str).strftime("%m/%d/%Y %H:%M:%S")
subprocess.run(
["SetFile", "-d", formatted, file_path],
check=True, capture_output=True, text=True,
)
updated += 1
except ValueError as e:
print(f"Couldn't parse date in {file_path}: {e}")
except subprocess.CalledProcessError as e:
print(f"SetFile failed for {file_path}: {e.stderr.strip()}")
except OSError as e:
print(f"Couldn't read {file_path}: {e}")
print(f"Updated {updated} file(s).")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python3 update_file_dates.py <directory>")
sys.exit(1)
if shutil.which("SetFile") is None:
print("SetFile not found. Install the Command Line Tools with: xcode-select --install")
sys.exit(1)
update_file_dates(sys.argv[1])
Usage
python3 update_file_dates.py /path/to/your/documents
This script can be easily adjusted to support .txt files, other date front matter like created, or other date formats, if needed. Reach out if you have any questions or recommendations for improvements.
-
Updated October 2026: the script now only reads dates from front matter and accepts quoted dates, reports
SetFileerrors instead of failing silently, and checks thatSetFileis installed before it starts. I’ve also added prerequisites, sinceSetFilecomes with Apple’s Command Line Tools rather than macOS itself. ↩︎