Best way to insert timestamp in Vim?

Viewed 40920

EditPad Lite has a nice feature (CTRL-E, CTRL-I) which inserts a time stamp e.g. "2008-09-11 10:34:53" into your code.

What is the best way to get this functionality in Vim?

(I am using Vim 6.1 on a Linux server via SSH. In the current situation a number of us share a login so I don't want to create abbreviations in the home directory if there is another built-in way to get a timestamp.)

11 Answers

To make it work cross-platform, just put the following in your vimrc:

nmap <F3> i<C-R>=strftime("%Y-%m-%d %a %I:%M %p")<CR><Esc>
imap <F3> <C-R>=strftime("%Y-%m-%d %a %I:%M %p")<CR>

Now you can just press F3 any time inside Vi/Vim and you'll get a timestamp like 2016-01-25 Mo 12:44 inserted at the cursor.

For a complete description of the available parameters check the documentation of the C function strftime().

:r! date

You can then add format to the date command (man date) if you want the exact same format and add this as a vim alias as well

:r! date +"\%Y-\%m-\%d \%H:\%M:\%S"

That produces the format you showed in your example (date in the shell does not use \%, but just %, vim replaces % by the name of the current file, so you need to escape it).

You can add a map in your .vimrc for it to put the command automatically, for instance, each time you press F3:

:map <F3> :r! date +"\%Y-\%m-\%d \%H:\%M:\%S"<cr>

(Edited the from above :) ) (Edit: change text part to code, so that

<F3> 

can be displayed)

For a unix timestamp:

:r! date +\%s

You can also map this command to a key (for example F12) in VIM if you use it a lot:

Put this in your .vimrc:


map  <F12> :r! date +\%s<cr>

I wanted a custom command :Date (not a key mapping) to insert the date at the current cursor position.

Unfortunately straightforward commands like r!date result in a new line. So finally I came up with the following:

command Date execute "normal i<C-R>=strftime('%F %T')<CR><ESC>"

which adds the date/time string at the cursor position without adding any new line (change to normal a add after the cursor position).

I'm using vi in an Eterm for reasons and it turns out that strftime() is not available in vi.

Fought long and hard and finally came up with this:

map T :r! date +"\%m/\%d/\%Y \%H:\%M" <CR>"kkddo<CR>

Result: 02/02/2021 16:45

For some reason, adding the date-time alone resulted in a blank line above the date-time and the cursor set on the date-time line.

date +"[etc]" <CR> Enters the date-time
"kk Moves up two lines
dd Deletes the line above the date-time
o <CR> Opens a line below the time and adds a carriage return (linefeed)

Bonus:

vi doesn't read ~/.vimrc, it reads ~/.exrc

Also, this is how it looks in vim/.vimrc:

map T  "=strftime("%m/%d/%y %H:%M")<CR>po<CR>
Related