Unable to add time to current time - python

start_time=datetime.time(9,00)
new_time=starttime+datetime(0,50) # I want new time as 9.50
But this throws me an error:
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'

please try the below python script:
from datetime import datetime
from datetime import timedelta
time = datetime(2013, 5, 31, 03, 00, 00)###or you can use time = datetime.datetime.now()
diff = timedelta(seconds = 60)
final_time = time + diff
print final_time

We can overload the operator, to do the above functionality, Please check the below code
class Mytime(datetime.time):
def __add__(self,b):
res = (self.hour*60+self.minute)+(b.hour*60+b.minute)
return Mytime(res/60,res%60)
start_time = Mytime(9,0)
next_time = start_time+Mytime(9,0)

Related

Transforming the current date and getting the date 7 days earlier

I need to transform dates to this format:
#(Optional) Start date in format YYYY-MM-DD%20HH:NN:SS.
To make api call and then get from it date 7 days earlier
from datetime import datetime, timedelta
end = datetime.now().strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start )
print("End: ", end )
I tried to do it this way but I get an error
unsupported operand type(s) for -: 'str' and 'datetime.timedelta'
Thanks to Peter Wood i fixed this silly mistake
end_time = datetime.now()
start_time = end_time - timedelta(days=7)
end = end_time.strftime("%Y-%m-%d%%20%H:%M:%S")
start = start_time.strftime("%Y-%m-%d%%20%H:%M:%S")
print("Start: ", start )
print("End: ", end )
With strftime you are casting end to string, remove that part like this:
from datetime import datetime, timedelta
end = datetime.now()#.strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start)
print("End: ", end)
If you want to format your output you can then add .strftime("%Y-%m-%d%%20%H:%M:%S") like this:
from datetime import datetime, timedelta
end = datetime.now()#.strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start.strftime("%Y-%m-%d%%20%H:%M:%S"))
print("End: ", end.strftime("%Y-%m-%d%%20%H:%M:%S"))
from datetime import datetime, timedelta
from urllib.parse import quote
end = datetime.now()
start = end - timedelta(days=7)
print("Start: ", quote(start.strftime("%Y-%m-%d %H:%M:%S")))
# Start: 2022-09-27%2008%3A28%3A11

How can I convert date to string in python?

I'm trying to convert it in a simple way using str() but it doesn't work. How can I do that?
import json
import datetime
def lambda_handler(event, context):
lastUpdate="2020-09-17 03:59:21+00:00"
now = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc)
diff = now - lastUpdate
print("Now:" + str(now) + lastUpdate)
Output:
errorMessage": "unsupported operand type(s) for -: 'datetime.datetime' and 'str'",
get the utc timezone and string format as below:
from datetime import datetime, timezone
lastUpdate="2020-09-17 03:59:21+00:00"
now2 = datetime.now(timezone.utc).strftime("%Y%m%d %H:%M:%S")
print("Now:" + str(now2) + lastUpdate)
for the differences, please parse string into two datetime objects and calculate the differences in days.
now3 = datetime.now(timezone.utc)
day = datetime.strptime(lastUpdate, '%Y-%m-%d %H:%M:%S%z')
print("now3= "+ str(now3))
print("day= " + str(day))
diffs = now3 - day
print('Total difference in minutes: ', str(diffs.days))
print("Now:" + str(now3) +" "+ lastUpdate + "Diff= " + str(diffs.days))
The datatype of 'now' is datetime and of 'lastUpdate' is str, you cannot get difference between different datatypes. Convert lastUpdate to datetime format first.
import json
from datetime import datetime, timezone
from dateutil import parser
def lambda_handler(event, context):
lastUpdate="2020-09-17 03:59:21+00:00"
lastUpdate = parser.parse("2020-09-17 03:59:21+00:00")
now = datetime.now(timezone.utc)
diff = now - lastUpdate
print("Now:" + str(now) + str(lastUpdate))
strftime-and-strptime-behavior
strftime-and-strptime-format-codes
from datetime import datetime
lastUpdate = "2020-09-17 03:59:21+00:00"
dt: datetime = datetime.strptime(lastUpdate, "%Y-%m-%d %H:%M:%S%z")
print(repr(dt))
# datetime.datetime(2020, 9, 17, 3, 59, 21, tzinfo=datetime.timezone.utc)
dt_str = dt.strftime("%Y-%m-%d %H:%M:%S")
print(repr(dt_str))
# '2020-09-17 03:59:21'

unsupported operand type(s) for %

today = date.today()
expire_date = date(today.year, 6, 7)
days = expire_date - today
left_months = days // 30
left_days = days % 30
'''
Error in this line : unsupported operand type(s) for %:
'datetime.timedelta' and 'int'
'''
print('{} Months'.format(left_months), '{} Days'.format(left_days) + " until exhibition day")
Taken from the answer to How do I convert days into years and months in python?, you can use the package dateutil.
from dateutil.relativedelta import relativedelta
from datetime import date
today = date.today()
expire_date = date(today.year, 6, 7)
rdelta = relativedelta(expire_date, today)
print(f'{rdelta.months} months {rdelta.days} days until exhibition day')
Also notice the usage of f-strings, as they are I believe more pythonic.

Not using the datetime module and even then get this, TypeError: 'DatetimeIndex'

Hi why do I get this error and how do I correct it?
File "<ipython-input-451-471e59eff2c7>", line 1, in <module>
range(6,31,7)
TypeError: 'DatetimeIndex' object is not callable
weekend_prime = []
weekends = []
weekday_prime=[]
def createWeekendData_Jan():
for dayy in range(6,31,7): #all Sat. and Sun. of Jan.
day_str = str(dayy)
if(len(day_str)==1):
day_str = '0'+day_str
for hours in range(1,24):
hours_str = str(hours)
if(len(hours_str)==1):
hours_str = ' 0'+hours_str
else:
hours_str = ' '+hours_str
weekends.append('2018-01-'+day_str+hours_str)
createWeekendData_Jan()
print(weekends)

How to calculate diff between two dates in django

I want to calculate days difference between current date and previous date.
i am trying this code
requiremntObj = CustomerLeads.objects.all()
a = datetime.datetime.now().date()
for i in requiremntObj:
date1=i.posting_date
diff = a-date1
print diff
I got a error unsupported operand type(s) for -: 'datetime.date' and 'unicode'
For current date i am getting datetime object and for date1 i am getting unicode.
posting_date = models.DateField()
If you have DateTimeField you can use:
delta = datetime.now().date() - posting_date
print delta.days
If it is string, then you have to convert:
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime(str(datetime.now().date()), date_format)
b = datetime.strptime(str(posting_date), date_format)
delta = b - a
print delta.days
Here is post.
This code for HTML in Django
<p> {{ to_date|timeuntil:from_date }} </p>
This code for server site in python
import datetime
from_date = datetime.datetime(2019, 10, 21)
to_date = datetime.datetime(2019, 10, 25)
result = to_date - from_date
print(result.days)

Categories