Skip to content

Instantly share code, notes, and snippets.

@mthomason
Created January 22, 2025 17:22
Show Gist options
  • Save mthomason/0374c821246cc864bb75f3c6137775b2 to your computer and use it in GitHub Desktop.
Save mthomason/0374c821246cc864bb75f3c6137775b2 to your computer and use it in GitHub Desktop.
Python script to add date-created property to Obsidian Markdown files.
# Add date created to Obsidian files, if they don't already exist.
import os
import datetime
import re
def get_creation_date(filepath):
"""Get the creation date of a file."""
stat = os.stat(filepath)
try:
# Attempt to get the creation time directly (works on some systems)
return datetime.datetime.fromtimestamp(stat.st_birthtime)
except AttributeError:
# Fallback to modification time if creation time is not available
return datetime.datetime.fromtimestamp(stat.st_mtime)
def format_date_iso(dt):
"""Format a datetime object into the ISO format: YYYY-MM-DDTHH:MM:SS."""
return dt.strftime("%Y-%m-%dT%H:%M:%S")
def add_date_created_to_file(filepath, date_created):
"""Add the date-created property to the YAML frontmatter of a Markdown file if it doesn't already exist."""
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
# Check if the file already has YAML frontmatter
frontmatter_pattern = re.compile(r'^---\s*\n.*?\n---\s*\n', re.DOTALL)
has_frontmatter = frontmatter_pattern.match(content)
# Check if the date-created property already exists
date_created_pattern = re.compile(r'^date-created:\s.*$', re.MULTILINE)
if has_frontmatter and date_created_pattern.search(content):
print(f"Property 'date-created' already exists in {filepath}. Skipping.")
return
# Format the date-created property
date_created_str = f"date-created: {format_date_iso(date_created)}\n"
# Add or update the frontmatter
if has_frontmatter:
# Insert date-created into existing frontmatter
new_content = frontmatter_pattern.sub(
lambda match: match.group(0).replace('---\n', f'---\n{date_created_str}', 1),
content
)
else:
# Add new frontmatter with date-created
new_content = f"---\n{date_created_str}---\n{content}"
# Write the updated content back to the file
with open(filepath, 'w', encoding='utf-8') as file:
file.write(new_content)
print(f"Added 'date-created: {format_date_iso(date_created)}' to {filepath}.")
def process_directory(directory):
"""Process all Markdown files in the given directory."""
for root, _, files in os.walk(directory):
for filename in files:
if filename.endswith('.md'):
filepath = os.path.join(root, filename)
creation_date = get_creation_date(filepath)
add_date_created_to_file(filepath, creation_date)
if __name__ == "__main__":
# Path to your Obsidian notes directory
obsidian_notes_directory = "/Users/michael/Projects/scratch/notes/Notes/Random"
# Check if the directory exists
if os.path.isdir(obsidian_notes_directory):
print(f"Processing directory: {obsidian_notes_directory}")
process_directory(obsidian_notes_directory)
print("Processing complete.")
else:
print(f"The directory {obsidian_notes_directory} does not exist.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment