zerosleeps

Since 2010

Sublime Text timestamp snippet

2 parts needed: a Python module to generate the string, and a definition to make the class available as a Sublime Text command.

The end result of all of this is a new Sublime Text command which outputs something like this at the current cursor position:

2019-05-01T19:53+1000

~/Library/Application Support/Sublime Text 3/Packages/User/date-time-stamp.py

Python module which defines a subclass of sublime_plugin.TextCommand and uses Sublime Text’s hooks to spew out a formatted datetime as a snippet.

Ever tried to get Python to output the local UTC offset? What a mess. My solution was shamelessly stolen from this Stack Overflow answer:

import time
import datetime
import sublime_plugin

class DateTimeStampCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        utc_offset_sec = time.altzone if time.localtime().tm_isdst else time.timezone
        utc_offset = datetime.timedelta(seconds=-utc_offset_sec)
        formatted_string = datetime.datetime.now().replace(tzinfo=datetime.timezone(offset=utc_offset)).strftime('%Y-%m-%dT%H:%M%z')

        self.view.run_command(
            "insert_snippet",
            {
                "contents": formatted_string
            }
        )

~/Library/Application Support/Sublime Text 3/Packages/User/date-time.sublime-commands

This surfaces the new class method in Sublime Text’s command pallet:

[
    {
        "caption": "Insert ISO8601 date and time",
        "command": "date_time_stamp"
    }
]