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....

2

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply, but I need to add particular time in present date ...not in time. kindly see e.g. once
@Addy: Got it. Edited.
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.

4 Comments

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.
It worked, but some default date come in output 2020-10-221900-01-01 12:00:00
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 ?
I got answer..but is it in datetime format??if no then how to convert this str into datetime

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.