Add time in Present date using Python - python

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

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

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.

Related

I am trying to subtract a date from todays date but it is telling me the operand type is unsupported in python

Both types of data have been converted into dates, and it still is telling me it can't subtract them. I've watched many tutorials and looked at stack overflow for hours, but all the solutions say that the only possible problem is an incorrect form of data which is not true. The error message is :
>unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'<
The text file contains only this:
Birthday 30/5/2021
def display():
with open ('countdown.txt', 'r') as file:
for line in file:
data = line.split(' ')
title = data[0]
date_str = data[1]
date = datetime.datetime.strptime(date_str, '%d/%m/%y')
time_between = datetime.date.today()-date
print(title + 'is' + time_between + 'days away!')
display()
One value is date+time and one is date only, they do not match. Replace datetime.date.today() with datetime.datetime.today().
The result will be a datetime.timedelta object.
There are two different date methods, one in datetime and one in date:
import datetime
dt = datetime.datetime.today()
print(dt, type(dt))
# 2020-12-10 20:45:20.661116 <class 'datetime.datetime'>
d = datetime.date.today()
print(d, type(d))
# 2020-12-10 <class 'datetime.date'>
As your date is a datetime object, you need to subtract it with another datetime, so you have to use:
time_between = datetime.datetime.today() - date

Python: Add minutes or seconds to a time only object

I need to add a given number of minutes or seconds to a Time object that comes without the date portion.
For Ex:
Time: 13:00:00 + 10 minutes (Should return 13:10:00)
Time: 21:50:00 + 1800 seconds (Should return 22:20:00)
My code:
from datetime import timedelta
d = timedelta(minutes=30)
calendar_entry + d #calendar_entry is a time object HH:MM:SS
Error:
During handling of the above exception (unsupported operand type(s)
for +: 'datetime.time' and 'datetime.timedelta'), another exception
occurred:
How can I do this in Python 3?
Try this:
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(13, 0)) + timedelta(minutes=10)
print (dt.time())
#13:10:00
Here's what you want:
import datetime
date = datetime.datetime.strptime('15:57:12', '%H:%M:%S')
print(date.strftime('%H:%M:%S'))
date = date+datetime.timedelta(seconds=1800)
print(date.strftime('%H:%M:%S'))
date = date+datetime.timedelta(minutes=30)
print(date.strftime('%H:%M:%S'))
Output:
15:57:12
16:27:12
16:57:12
This way of manipulation is only possible with datetime objects, but luckily, you can do the conversion from datetime to time, to have it your way. Take a look at add_minutes:
import datetime
def add_minutes(tm, minutes1):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(minutes=minutes1)
return fulldate.time()
a = datetime.datetime.now().time()
b = add_minutes(a, 2)
print(a)
print(b)

TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'

I am new to python date and time types.
I have a date value.
date = '2018-11-10 10:55:31+00:00'
I need to check this date value is older than 90 days.
I tried :
from datetime import datetime
from datetime import timedelta
past = datetime.now() - timedelta(days=90)
date = '2018-11-10 10:55:31+00:00'
if past > date :
print("This is older than 90 days")
failing with the following error :
TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'
This might be because the date format for 'past' and the date value which I passed is different.
How can I come up with this ?
You have to use strptime to convert a string into a date.
The comparaison operator only applies between datetime.
date = datetime.strptime('2018-11-10 10:55:31', '%Y-%m-%d %H:%M:%S')
then can you do
if past > date :
print("This is older than 90 days")
You can use dateutil package and just convert your date string date to `datetime object and then check the condition with :
from dateutil import parser
past = datetime.now() - timedelta(days=90)
new_date = parser.parse("2018-11-10 10:55:31+00:00")
if past > new_date :
print("This is older than 90 days")
that it : )
You need to convert your date string to datetime. You can do this in a couple of ways.
Use built-in datetime.strptime
For example, first convert to datetime before your comparison. This requires you to specify the format precisely ahead of time:
date = '2018-11-10 10:55:31+00:00'
date = datetime.strptime(date[:-6], '%Y-%m-%d %H:%M:%S')
print(date)
datetime.datetime(2018, 11, 10, 10, 55, 31)
Use a 3rd party library
One popular tool is dateutil.parser, which is able to parse most common datetime formats without the format specified in advance:
from datetime import datetime, timedelta
from dateutil import parser
past = datetime.now() - timedelta(days=90)
date1 = '2018-11-10 10:55:31+00:00'
date2 = '2017-11-10 10:55:31+00:00'
for date in (date1, date2):
if past > parser.parse(date[:-6]):
print(f'This is older than 90 days: {date}')
This is older than 90 days: 2017-11-10 10:55:31+00:00

Python datetime add

I have a datetime value in string format. How can I change the format from a "-" separated date to a "." separated date. I also need to add 6 hours to let the data be in my time zone.
s = '2013-08-11 09:48:49'
from datetime import datetime,timedelta
mytime = datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
time = mytime.strftime("%Y.%m.%d %H:%M:%S")
dt = str(timedelta(minutes=6*60)) #6 hours
time+=dt
print time
print dt
I get the following result where it adds the six hours at the end and not to the nine:
2013.08.11 09:48:496:00:00
6:00:00
You are adding the string representation of the timedelta():
>>> from datetime import timedelta
>>> print timedelta(minutes=6*60)
6:00:00
Sum datetime and timedelta objects, not their string representations; only create a string after summing the objects:
from datetime import datetime, timedelta
s = '2013-08-11 09:48:49'
mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
mytime += timedelta(hours=6)
print mytime.strftime("%Y.%m.%d %H:%M:%S")
This results in:
>>> from datetime import datetime, timedelta
>>> s = '2013-08-11 09:48:49'
>>> mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
>>> mytime += timedelta(hours=6)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
However, you probably want to use real timezone objects instead, I recommend you use the pytz library:
>>> from pytz import timezone, utc
>>> eastern = timezone('US/Eastern')
>>> utctime = utc.localize(datetime.strptime(s, "%Y-%m-%d %H:%M:%S"))
>>> local_tz = utctime.astimezone(eastern)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
This will take into account daylight saving time too, for example.

Python 2 Different Date Time in Second

from datetime import datetime, date, time
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.now
time.sleep(5)
d2 = datetime.now
diff = (d2-d1).seconds
print(diff)
i get the error message with
diff = (d2-d1).seconds
TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'builtin_function_or_method'
how to different the two datetime in seconds format?
You are missing your brackets () after now:
from datetime import datetime, date, time
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.now()
time.sleep(5)
d2 = datetime.now()
diff = (d2-d1).seconds
print(diff)
now is a function, so what you are trying to subtract are two functions. Try this:
datetime.now() - datetime.now()
The problem is that you are not calling the datetime.now function, you are merely assigning d1 and d2 to the reference of the function. This should solve your problem:
d1 = datetime.now() # note the function call
d2 = datetime.now()

Categories