Insert the current date or time

3.2
(542)

We’ve heard from a lot of you that you use Vim for editing all kinds of text, including notes, journals, wikis, and much more. Many of these types of writing can often benefit from inserting the current date or date and time. Rather than checking a clock and manually typing it, there are several ways Vim can insert the current date and time. Here are two ways:

  • :r! date – Uses your system’s date command and reads the results into the line below. This is dependent on your underlying system having a date command. On Windows, use date \t.
  • :put =strftime('%B %e')– Uses Vim’s strftime function to insert a date time using standard strftime formatting.

I find :r! date to be easier and quicker to type so if I’m just writing notes and need a quick timestamp, that’s my preferred method. Using strftime gives us total control over the format and is necessary for more precise usages. Again note that strftime uses the runtime that Vim uses under the hood, which means formatting can vary across platforms such as Windows. In practice on Mac/*nix you can probably use the Linux strftime man page reference for formatting codes.

Here’s a short screencast showing several date inserts, first by shelling out and reading the results of the date command into the buffer with :r! date. And then by using strftime to insert a more human-friendly date format.

If you often need to insert a specific date format, you could add a custom command to your Vim configuration. For example, add this to your .vimrc:

map <leader>D :put =strftime('# %a %Y-%m-%d %H:%M:%S%z')<CR>

Now, anytime you want to insert a Markdown-style header with the current date and time, just press<leader>D (the default leader key in Vim is \). A new line with the current date and time, formatted per the strftime format, will be inserted below — great for note-taking or journaling.

How useful was this tip?

Average rating 3.2 / 5. Vote count: 542

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts