3
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) } )

我已将上面的代码保存为time.py 并将命令映射到热键以在编辑器中插入昨天和明天的日期。

我在这里做错了什么?

4

1 回答 1

3

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))}
于 2013-11-13T18:35:23.883 回答