Date/Time SublimeText Plugin

published on 2023-12-07 in computing

I keep a daily log in a markdown doc and have been manually typing the day and time in for a few months now. My editor is SublimeText, which supports python plugins so I figured this could be done pretty easily. Here's what I came up with after a few minutes:

  1. In Sublime Text, go to "Tools" > "Developer" > "New Plugin...".
  2. Replace the default code with the following Python script:
import sublime
import sublime_plugin
from datetime import datetime, timezone

class InsertDateTimeCommand(sublime_plugin.TextCommand):
    def run(self, edit, date_or_time):
        if date_or_time == "date":
            content = self.generate_date_string()
        elif date_or_time == "time":
            content = self.generate_time_string()
        else:
            return

        self.insert_content(edit, content)

    def generate_date_string(self):
        now = datetime.now()
        formatted_date = now.strftime("%A %Y-%m-%d")
        return f"{formatted_date}\n{'=' * len(formatted_date)}"

    def generate_time_string(self):
        now = datetime.now(timezone.utc)
        local_time = now.astimezone()
        utc_time = now.strftime("%H:%M:%S UTC")
        local_time_str = local_time.strftime("%I:%M:%S %p %Z")
        return f"{local_time_str} ({utc_time})"

    def insert_content(self, edit, content):
        for region in self.view.sel():
            self.view.insert(edit, region.begin(), content + '\n')
  1. Save the file with somethign like insert_date_time.py in your Sublime Text "Packages" directory.

  2. Now, you can create a key binding to trigger this command. Go to "Preferences" > "Key Bindings" and add a binding similar to the following:

[
    { "keys": ["ctrl+shift+d"], "command": "insert_date_time", "args": {"date_or_time": "date"} },
    { "keys": ["ctrl+shift+t"], "command": "insert_date_time", "args": {"date_or_time": "time"} }
]

Now, when you press ctrl+shift+d, it will insert the current date, and pressing ctrl+shift+t will insert the current time along with UTC time.

Looks like this:

Thursday 2023-12-07
===================

And this:

12:38:05 PM CST (18:38:05 UTC)
Tags: python