大家好,我是一个学习python的新手,我只想打印当前时间以x开头的内容(例如,如果当前时间以= 4开始,则打印" Hi ",time = 4:18),这是我编写的代码,它显示属性错误:
import datetime
local = datetime.datetime.now().time().replace(microsecond=0)
if local.startswith('16'):
print("Hi! It's ", local)发布于 2019-08-06 22:23:50
.replace()方法返回一个date对象。date对象没有.startswith()方法。该方法仅适用于str。
请先尝试将日期转换为字符串:
if str(local).startswith('16'):
print("Hi! It's ", local)The documentation列出了date对象上所有可用的方法。
发布于 2019-08-06 22:24:32
您需要首先将其转换为string,因为datetime对象没有startswith()方法。使用strftime,示例:
import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t2 = t.strftime('%m/%d/%Y')将产生:
'02/23/2012'。一旦它被转换,你就可以使用t2.startswith()了。https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
发布于 2019-08-06 22:29:58
您可以获取该时间的小时数,并检查是否为16:
if local.hour == 16:
print("Hi! It's ",local)如果您需要使用startswith(),则可以将其转换为如下所示的字符串:
if str(local).startswith('16'):
print("Hi! It's ", local)https://stackoverflow.com/questions/57378200
复制相似问题