如何解决TypeError:无法将datetime.datetime类型与字符串拼接
Python字符串与datetime对象拼接错误解决
你的错误出在print语句里——Time是datetime.datetime类型的对象,Python不允许直接把字符串和datetime对象用+拼接。不过你已经通过strftime()生成了格式化好的字符串dt_string,直接用它替换Time就能解决问题。
修正后的代码(基础版)
from datetime import datetime import os current_time = datetime.now() dt_string = current_time.strftime("%d/%m/%Y %H:%M:%S") print("Welcome " + os.getlogin() + " the current date and time is:" + dt_string)
更简洁的写法(推荐用f-string)
f-string是Python 3.6及以上版本支持的字符串格式化方式,代码更易读,也能避免拼接错误:
from datetime import datetime import os current_time = datetime.now() dt_string = current_time.strftime("%d/%m/%Y %H:%M:%S") print(f"Welcome {os.getlogin()} the current date and time is: {dt_string}")
另外,你导入的date模块没有被使用,可以删掉,减少代码冗余。
内容的提问来源于stack exchange,提问作者Gamefox06
相关产品推荐
相关产品推荐

