Skip to content

Instantly share code, notes, and snippets.

@alexjj
Created December 6, 2021 12:38

Revisions

  1. alexjj created this gist Dec 6, 2021.
    53 changes: 53 additions & 0 deletions opml-to-md-files.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    import pathlib
    from datetime import datetime
    from xml.etree import ElementTree

    def process_date(date):
    """
    Converts opml created date into python datetime object
    """
    datetime_object = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z')
    return datetime_object


    def create_front_matter(date_object):
    """
    Creates the front matter in my notes from a date.
    Format:
    ---
    title: Monday, 6th December, 2021
    date: 2021-12-06 00:00
    ---
    """

    # https://stackoverflow.com/a/66364403/2000527
    n = date_object.day
    ordindal = f"{n:d}{'tsnrhtdd'[(n//10%10!=1)*(n%10<4)*n%10::4]}"

    title = date_object.strftime(f'%A, {ordindal} %B, %Y')
    date = date_object.strftime("%Y-%m-%d %H:%M:%S")

    return (
    '---\n'
    f'title: {title}\n'
    f'date: {date}\n'
    'published: false\n'
    '---\n'
    )


    with open('blog.opml', 'rt', encoding='utf-8') as f:
    tree = ElementTree.parse(f)

    for node in tree.findall('.//outline'):
    type = node.attrib.get('type')
    name = node.attrib.get('name')
    date = node.attrib.get('created')
    if name and type != "calendarMonth":
    datetime_object = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z')

    # create file with name YYYY-MM-DD-day.md
    filename = datetime_object.strftime("%Y-%m-%d-%A").lower() + '.md'
    file = pathlib.Path.cwd() / 'posts' / filename
    # Add front matter contents
    file.write_text(create_front_matter(process_date(date)))