You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 08:47:09