5

I can use \=expr in :s command. For example, to convert timestamps format inplace:

:%s/\v<\d{10}>/\=strftime('%c', submatch(0))/g

But the functionality of built-in functions are so limited. To parse a timestamp, I'd like to use python script like this:

$ python
>>> import datetime
>>> d = 'Apr 11 2012'
>>> datetime.datetime.strptime(d, '%b %d %Y').isoformat()
'2012-04-11T00:00:00'

How to embed this py-expr into :s command?

:%s/\v\w+ \d{2} \d{4}/\={?py-expr?}/g

Thanks!

1
  • Note: if you believe vim doc, space may have a special meaning and thus needs to be escaped in very-magic mode. Only 0-9, a-z, A-Z and _ ASCII characters are said explicitly to have no special meaning in this mode. Commented Nov 4, 2012 at 17:27

1 Answer 1

8

If you have at least vim-7.3.569 then you may do the following:

:python import datetime
:%s/\v\w+\ \d{2}\ \d{4}/\=pyeval('datetime.datetime.strptime(vim.eval("submatch(0)"), "%b %d %Y").isoformat()')/g

. If you don’t you have recent vim you can emulate pyeval in this case:

function Pyeval(expr)
    python import json
    python vim.command('return '+json.dumps(eval(vim.eval('a:expr'))))
endfunction

, then replace pyeval in the above code with Pyeval.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.