How to calculate diff between two dates in django - python

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)

Related

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'

How to replace the day in a date with another date?

I'm trying to replace the day in my if statement for my date but I keep getting this output for my year.
05/15/5 besides 05/15/2020 . Code is below:
today_date = datetime.datetime.now()
date = today_date.date()
formatted_date = datetime.date.strftime(date, "%m/%d/%Y")
mmonth = date.month
myear = date.year
mdate = date.day
if mdate < 7:
m0weekend = formatted_date.replace(str(myear),str(mmonth),1)
else:
m0weekend = formatted_date.replace(str(myear),str(mmonth),15)
it's easier to replace the day before converting to a string:
date = date.replace(day=1)
or, in your case:
if mdate < 7:
m0weekend = date.replace(day=1)
else:
m0weekend = date.replace(day=15)
formatted_date is actually a string.
You are using the str.replace() method not the datetime.date.replace() method.
import datetime
today_date = datetime.datetime.now()
pre_formatted_date = today_date.date()
mmonth = pre_formatted_date.month
myear = pre_formatted_date.year
mdate = pre_formatted_date.day
if mdate < 7:
pre_formatted_date = pre_formatted_date.replace(day=1)
else:
pre_formatted_date = pre_formatted_date.replace(day=15)
print(pre_formatted_date)
formatted_date = pre_formatted_date.strftime("%m/%d/%Y")
print(formatted_date)
Which has the following output:
2020-05-15
05/15/2020
You might get today datetime.date directly from datetime rather than creating datetime.datetime and converting to date. After you have today you might create needed datetime.date and turn it into str, i.e.:
import datetime
today = datetime.date.today()
date = datetime.date(today.year, today.month, 1 if today.day < 7 else 15)
formatted_date = datetime.date.strftime(date, "%m/%d/%Y")
print(formatted_date) # 05/15/2020

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.

Django built-in timesince filter to show only Days

I am using {{ prospect.date_1 }} - ({{ prospect.date_1|timesince }} ago) in my template to get time since the date.
The point is, date_1 is a date not datetime, so when i apply the filter it tells me like
July 18, 2014 - (11 hours, 39 minutes ago)
expected output
July 18, 2014 - (0 days ago)
taken from naturalday
#register.filter(expects_localtime=True)
def days_since(value, arg=None):
try:
tzinfo = getattr(value, 'tzinfo', None)
value = date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't a date object
return value
except ValueError:
# Date arguments out of range
return value
today = datetime.now(tzinfo).date()
delta = value - today
if abs(delta.days) == 1:
day_str = _("day")
else:
day_str = _("days")
if delta.days < 1:
fa_str = _("ago")
else:
fa_str = _("from now")
return "%s %s %s" % (abs(delta.days), day_str, fa_str)
results
>>> days_since(datetime.now())
'0 days ago'
>>> days_since(date(2013, 5, 12))
'432 days ago'
>>> days_since(date(2014, 12, 12))
'147 days from now'
>>> days_since(date(2014, 7, 19))
'1 day from now'
#Jack, Have you tried to use in-built python:
Visit: https://docs.python.org/2/library/datetime.html#datetime.datetime.day
Also if this might help:
https://docs.djangoproject.com/en/1.6/ref/contrib/humanize/#naturaltime
Edit:
from datetime import date
from datetime import datetime
d = date.today()
datetime.combine(d, datetime.min.time())

Unable to add time to current time

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)

Categories