Twitter Email
subspace (/ˈsʌbspɛɪs/)
A Jekyll playground site

Sublime Text 4 Plugin to insert current date and time

Author: Admin
Title: Sublime Text 4 Plugin to insert current date and time
Language: en-US
Category: Sublime
Created: 04:33 on Friday, 12. November 2021
Modified: 04:33 on Friday, 12. November 2021
Keywords: sublimetext, sublime, plugin, time, date
Excerpt:

A simple python plugin that can insert the current date and time at the cursor position using a variety of different formats.

Tags: sublime
Page layout: nonav
Last modified: , 234 Words
04:33 on Friday, 12. November 2021 | by Admin in Sublime

This is a simple python plugin that just inserts the current date and time at the cursor position. It uses ISO date and time format as default, but can be told to use the system format instead.

It creates a new text command insert_datetime that takes one optional argument (the date format) which can be either ìso (the default) or system to print the full date and time in system format. To use it, you’ll have to create keyboard mappings (see the comment in the source code)

Code: (click to select all)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 import sublime, sublime_plugin, time
 from datetime import datetime

 # insert a date string. optional argument 'format' specifies the format
 # 'sys': the system format (ctime())
 # 'iso': ISO format (default)

 # suggested keyboard bindings

 #  { "keys": ["ctrl+f5"], "command": "insert_datetime"},
 #  { "keys": ["f5"], "command": "insert_datetime", "args": {"format": "iso"}},
 #  { "keys": ["shift+f5"], "command": "insert_datetime", "args": {"format": "system"}},


 class insert_datetimeCommand(sublime_plugin.TextCommand):
   def run(self, edit, **kwargs):
     frm: str = 'iso'              # the format
     output: str = None
     if 'format' in kwargs:
       if kwargs['format'] == 'system':
         output = time.ctime()
       elif 'format' == 'iso':
         pass
       else:
         pass

     # iso format is the default
     if output is None:
         output = datetime.now().astimezone().replace(microsecond=0).isoformat()

     sel = self.view.sel();
     for s in sel:
       self.view.replace(edit, s, output)