Doing Time (in Python)

Posted by Grego on January 4, 2017

example vim completion

For the sake of making editing my blog easier I decided to add a new UltiSnips snippet for creating a relative path to where I keep images for posts, based on convention.

Generally I keep my images for my posts in a separate structure from the posts themselves in the path /img/year/month/day/image-name.png. To do this in UltiSnips I borrowed some functionality of Python for manipulating time. With a little help it turns out it’s really very simple.

In python:

import time
print(time.strftime("%Y/%m/%d/"))

Which would print

2017/01/04/

Now combining this in an UltiSnips snippet:

snippet /im "image link"
/${1:img}/${2:`!p import time; snip.rv = time.strftime("%Y/%m/%d/")`}${0}
endsnippet

The `!p ... ` creates a snippet of python interpreted code, in UltiSnips snip.rv represents the return value for that python snippet so it will return time.strftime(...) to the UltiSnips snippet on expansion.

The snippet creates two place holders, the first is the name of the base image directory and the second inserts the date in yyyy/mm/dd/ format. It is triggered by typing /im and pressing TAB.

I’ve definitely done something similar before but I don’t think I did it the same way.