【问题标题】:Add time in Present date using Python使用 Python 在当前日期中添加时间
【发布时间】:2020-10-22 15:20:46
【问题描述】:

我想在当前日期添加特定时间。 例如2020-10-22 12:00:00。 为此,我尝试了以下方式

from datetime import datetime, timedelta, date
duration = "12:00:00"
duration_obj = datetime.strptime(duration, '%H:%M:%S')
Date_Time = date.today() + duration_obj

但是,我遇到了错误

TypeError: unsupported operand type(s) for +: 'datetime.date' and 'datetime.datetime'

任何建议都会有所帮助....

【问题讨论】:

标签: python date datetime


【解决方案1】:

您可以使用fromisoformat12:00:00 转换为datetime.time 对象,将其转换为秒并添加到实际时间:

from datetime import datetime, timedelta, date, time
duration = "12:00:00"
duration_obj = time.fromisoformat(duration)
total_seconds = duration_obj.second + duration_obj.minute*60 + duration_obj.hour*3600

Date_Time = datetime.now() + timedelta(seconds=total_seconds)
print(datetime.now())
print(Date_Time)

输出:

2020-10-22 17:30:15.878372
2020-10-23 05:30:15.878357

编辑(使用 datetime.combine):

from datetime import datetime, timedelta, date, time
duration = "12:00:00"
duration_obj = time(*(int(x) for x in duration.split(':')))
Date_Time = datetime.combine(date.today(), duration_obj)
print(Date_Time)
>>>2020-10-22 12:00:00

直接构造日期时间对象:

duration = "12:00:00"
_today = date.today()

datetimeList = [_today.year, _today.month, _today.day] + [int(x) for x in duration.split(':')]
Date_Time = datetime(*datetimeList)
print(Date_Time)
>>> 2020-10-22 12:00:00

【讨论】:

  • 感谢您的回复,但我需要在当前日期添加特定时间...不是及时。请看,例如一次
  • @Addy:知道了。已编辑。
【解决方案2】:

在连接之前将它们转换为string

separator = " | " 
date_time = str(date.today()) + separator + duration

错误告诉您这些操作数:datetime.datedatetime.datetime 对象对于 + 连接操作无效。

【讨论】:

  • 您至少应该在字符串之间添加一个分隔符 ;-) ...应该提到的是,这会返回一个字符串,而 OP 的代码表明他想要一个日期时间对象。
  • 它有效,但输出中有一些默认日期2020-10-221900-01-01 12:00:00
  • Okei 抱歉,我不太明白您为什么要将12:00:00 转换为datetime,然后再将其转换回string?你可以像我上面那样做吗?
  • 我得到了答案..但它是日期时间格式吗??如果没有,那么如何将此 str 转换为日期时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多