Tom Shen
Cleaning up Roam Research export metadata

Roam Research allows you to easily export your notes, but the file metadata on the exported Markdown files is set to the current server time. This can be an issue if, for example, you import them into other note-taking applications that sort notes by modification date.

However, the JSON export for notes does have this metadata, so I wrote a small Python script that would allow me to use the metadata from the JSON export while still using the Markdown exported files instead of having to format them myself.

"""
Use Roam Research JSON export metadata to set the correct file metadata on Roam
Research Markdown export files.

Usage
  ./roam-export.py $EXPORT_JSON_FILE $EXPORT_MARKDOWN_DIRECTORY
"""

import datetime
import json
import os
import sys

def process_roam_export(export_json_filename, export_markdown_folder):
    export_data = import_export_json(export_json_filename)

    for note_data in export_data:
        set_note_file_metadata(
            os.path.join(export_markdown_folder, note_data['title'] + '.md'),
            note_data)

def import_export_json(export_json_filename):
    with open(export_json_filename) as f:
        return json.load(f)

def set_note_file_metadata(note_markdown_filename, note_data):
    note_file_stat = os.stat(note_markdown_filename)
    edit_time = note_data['edit-time'] / 1000
    os.utime(note_markdown_filename, (edit_time, edit_time))
    print(
        'Setting modification date of',
        '"' + note_data['title'] + '"',
        'to',
        datetime.date.fromtimestamp(edit_time)) 

if __name__ == '__main__':
    process_roam_export(sys.argv[1], sys.argv[2])