【问题标题】:How to convert datetime from tkcalendar to string?如何将日期时间从 tkcalendar 转换为字符串?
【发布时间】:2020-03-02 21:14:14
【问题描述】:

我正在创建一个从用户那里获取日期的程序,现在我需要转换为字符串,因为我需要将这些数据放入我正在实现的命令 shell 中,使用 tkinter 和 tkcalendar(lib 为我提供进入)。 我该怎么做?

这里是我要在 git 上运行的代码:

cal = Calendar(top, font='Arial 14', selectmode='day', cursor='hand1')
subprocess.call('git log --pretty='"format: % h"' --after=' +cal+' --before='+cal, shell=True)

【问题讨论】:

  • @wjandrea 我试过了,这是终端的例外:Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files (x86)\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "window.py", line 29, in calendar cal.strtime('%Y/%m/%d')+' --before='+cal.strtime('%Y/%m/%d'), shell=True) AttributeError: 'Calendar' object has no attribute 'strtime'
  • 你需要使用Calendar对象的datetime属性,然后是strftime,而不是strtime
  • 很抱歉,但是,看起来:Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files (x86)\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "window.py", line 28, in calendar subprocess.call('git log --pretty='"format: % h"' --after=' + cal.datetime.strftime( TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' object

标签: python python-3.x tkinter


【解决方案1】:

在您的情况下,cal 是一个 Calendar 实例,cal.datetime 返回 python 的 datetime 对象,该对象具有 strftime 以将日期时间格式化为字符串:

dt = cal.datetime.strftime("%Y-%m-%d")
subprocess.call(f"""git log --pretty="format: %h" --after={dt} --before={dt}""", shell=True)

【讨论】:

  • 我使用日历库的问题,我不会改变这个。如何从日历转换?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
相关资源
最近更新 更多