0

I want to add particular time in present date. e.g. 2020-10-22 12:00:00. For that I have tried in the following way

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

But , I'm gettimg an error

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

Any suggestion will be helpful....

Addy
  • 25
  • 5
  • Does this answer your question? [How to construct a timedelta object from a simple string](https://stackoverflow.com/questions/4628122/how-to-construct-a-timedelta-object-from-a-simple-string) – FObersteiner Oct 22 '20 at 15:27
  • Or: https://stackoverflow.com/questions/8474670/pythonic-way-to-add-datetime-date-and-datetime-time-objects – FObersteiner Oct 22 '20 at 15:30

2 Answers2

1

Transform them into string before concatenation:

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

The error is telling you that those operands: datetime.date and datetime.datetime object are not valid for + concatenation operation.

Nja
  • 439
  • 6
  • 17
  • you should at least add a separator between the strings ;-) ...and it should be mentioned that this returns a string whilst the OP's code suggests he wants a datetime object. – FObersteiner Oct 22 '20 at 15:33
  • It worked, but some default date come in output **2020-10-221900-01-01 12:00:00** – Addy Oct 22 '20 at 15:34
  • Okei sorry, i don't get well why you want to transform `12:00:00` into a `datetime` and then convert it back to `string` ? May you do as i did above ? – Nja Oct 22 '20 at 15:40
  • I got answer..but is it in datetime format??if no then how to convert this str into datetime – Addy Oct 22 '20 at 15:50
1

You can convert 12:00:00 to datetime.time object using fromisoformat, convert that to seconds and add it to the actual 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)

Out:

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

Edit (using 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

Construct the datetime object directly:

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
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47