Question

import datetime, getpass from datetime 
import timedelta import sublime, sublime_plugin

class TommorowCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.run_command("insert_snippet", { "contents": "%s" %  datetime.date.today() + datetime.timedelta(days=1) } )

class YesterdayCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.run_command("insert_snippet", { "contents": "%s" %  datetime.date.today() - datetime.timedelta(days=1) } )

I have saved the above code as time.py and mapped the commands to hotkey to insert yesterday's and tommorow's date in the editor.

What am I doing wrong here?

Was it helpful?

Solution

You need to add parenthesis to group the datetime arithmetic together:

{"contents": "%s" % (datetime.date.today() + datetime.timedelta(days=1))}

because the + operator has a lower precedence than the % operator:

>>> "%s" % datetime.date.today() + datetime.timedelta(days=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'datetime.timedelta' objects
>>> "%s" % (datetime.date.today() + datetime.timedelta(days=1))
'2013-11-14'

In the first form, Python evaluated "%s" % datetime.date.today() first and then you end up adding a string and a timedelta() object.

You could just use str() here:

{"contents": str(datetime.date.today() + datetime.timedelta(days=1))}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top