Vim Tip: How to Insert the Current Time with a Shortcut
Table of Contents ๐
When keeping a journal, logging meetings, or documenting events, an accurate timestamp is invaluable. However, manually typing the time is cumbersome and interrupts your writing flow.
In this short guide, youโll learn how to use a single, clever line in your .vimrc
to create a shortcut that lets you insert the current time instantly and effortlessly at any position.
The Solution: A Shortcut for Insert Mode
This method is ideal when youโre in the middle of writing and want to insert a timestamp directly into the text, for example:
14:32 โ Call from the project manager
To do this, simply add the following line to your ~/.vimrc
:
" Insert the current time (HH:MM) in insert mode with <leader>t
inoremap <leader>t <C-R>=strftime('%H:%M')<CR>
How It Works
This single line is a perfect example of Vimโs power:
inoremap <leader>t
: Defines a key mapping (by default\t
) exclusively for insert mode.<C-R>=
: This is the magic part. In insert mode,Ctrl-R
normally inserts the content of a register. When you add an equals sign (=
), Vim opens a mini-command line and evaluates the following expression.strftime('%H:%M')
: This is a built-in Vim function that returns the current time, formatted.%H
stands for the hour (24h) and%M
for the minute.<CR>
: Confirms the function, inserts its result (the time) at the cursorโs position, and seamlessly returns you to insert mode.
How to use it: The next time youโre typing in a note, just press \
followed by t
, and the current timestamp will appear instantly in the text.
Customize It to Your Needs
The best part of this method is its flexibility. You can customize the timestamp format however you like by changing the string inside the strftime()
function.
Here are a few popular alternatives for your .vimrc
:
" -- EXAMPLE 1: Time with seconds --
inoremap <leader>ts <C-R>=strftime('%H:%M:%S')<CR>
" -- EXAMPLE 2: Full date and time (ISO standard) --
inoremap <leader>dt <C-R>=strftime('%Y-%m-%d %H:%M')<CR>
" -- EXAMPLE 3: US Date Format --
inoremap <leader>us <C-R>=strftime('%m/%d/%Y %I:%M %p')<CR>
Bonus: Inserting a Timestamp in Normal Mode
Sometimes you might want to insert a timestamp on its own new line. For that, a normal mode shortcut is better suited.
" Insert the current time on a new line below the current one
nnoremap <leader>T :put =strftime('%H:%M')<CR>
With this mapping, you can press \T
in normal mode, and the time will be placed cleanly on the next line.
Summary
With this simple trick, youโve further optimized your workflow:
โ
You can insert timestamps instantly with a keystroke, without interrupting your flow.
โ
The format is fully customizable to your needs.
โ
The solution is lean, fast, and uses built-in Vim features without any extra plugins.
โน๏ธ WHAT'S NEXT? |
Now that youโve mastered timestamps, discover how to perfect links, navigation, and task management in our Vimwiki Workflow Guide. |