I have a question about my script. I want to know all people who have more than 16 years from my Database. I want to check this when user triggers the function.
I have this function :
def Recensement_array(request) :
date = datetime.now().year
print date # I get year from now
birthday = Identity.objects.values_list('birthday', flat=True) # Return list with all birthday values
for element in birthday :
if date - element < 117 :
print "ok < 117"
else :
print "ok > 117"
From print date I get :
2017
From print birthday I get :
<QuerySet [datetime.date(1991, 12, 23), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1089, 9, 22), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1990, 12, 12)]>
So my goal is to substract date with birthday and compare if date - birthday = 16 years, I print element, else nothing.
I get two problems :
How extract only year from birthday ?
Then the comparison method is between int and tuple up to now. If I could extract only year from birthday, it should work right ?
Thank you
EDIT :
For example I want to get all people who had 16 years old since the begining of this year or will get 16 years old before the first year :
def Recensement_array(request) :
today = datetime.now()
age_16 = (today - relativedelta(years=16))
result = Identity.objects.filter(birthday__range=[age_16, today]).order_by('lastname')
paginator = Paginator(result, 3)
page = request.GET.get('page', 1)
try:
result = paginator.page(page)
except PageNotAnInteger:
result = paginator.page(1)
except EmptyPage:
result = paginator.page(paginator.num_pages)
context = {
"Identity":Identity,
"age_16":age_16,
"datetime" : datetime,
"result" : result,
"PageNotAnInteger":PageNotAnInteger,
}
return render(request, 'Recensement_resume.html', context)
If you need filter records with some specific year you can just use __year method of date field:
age_16 = (today - relativedelta(years=16))
result = Identity.objects.filter(birthday__year=age_16.year).order_by('lastname')
Related
This is my function
def offer(rent_start, rent_end, website):
driver.get(website[0])
driver.find_element_by_xpath('//input[#id="btnUpdateQuote"]').click()
This is my 1st for loop
phones = ["https://xxxxxx/", "phones"]
laptops = ["https://xxxxxx/", "laptops"]
headsets = ["https://xxxxxx/", "headsets"]
keyboards = ["https://xxxxxx/", "keyboards"]
websites_list = [phones,laptops,headsets,keyboards]
for website in websites_list:
offer(rent_start, rent_end, website)
I would like to add the following 2nd for loop in my code, so that first the date is selected and then the website opened. So for example 17 June 2021 selected and then [phones,laptops,headsets,keyboards] are requested. After that 19 June 2021 (+ 2 days) is selected and [phones,laptops,headsets,keyboards] are requested
rent_start = date(2022, 6, 19)
add_to_rent_start = int(2)
alternate_days = timedelta(days=add_to_rent_start)
rent_end = rent_start + alternate days
alternate_days_list = [2, 4, 6, 8]
for alt_days in alternate_days_list:
alternate_days = timedelta(days=add_to_rent_start)
alternate_days_list = [2, 4, 6, 8]
for alt_days in alternate_days_list:
rent_start = date(2022, 6, 19)
alternate_days = timedelta(days=alt_days)
rent_end = rent_start + alternate days
for website in websites_list:
offer(rent_start, rent_end, website)
Then, you can request each URL with alternate_days_list.
I am creating a Jarvis style screen and have pulled data from outlook for upcoming meetings that I wish to present on the screen.
The function pulls data from outlook and presents it in a list: -
event(Start=datetime.datetime(2020, 11, 30, 12, 30), Subject='meeting 1 description',
Duration=60)
event(Start=datetime.datetime(2020, 11, 30, 14, 0), Subject='meeting 2 description', Duration=60)
event(Start=datetime.datetime(2020, 12, 1, 8, 30), Subject='meeting 3 description', Duration=60)
event(Start=datetime.datetime(2020, 12, 1, 10, 15), Subject='meeting 4 description', Duration=45)
event(Start=datetime.datetime(2020, 12, 1, 11, 0), Subject='meeting 5 description ',
Duration=90)"
This is great, but what I want to do now is have this present as:
Start time = 'start time'
Subject = 'Meeting description'
Duration = 'duration of meeting'
Is there a way of slicing up the string in a list item and then pulling that into the code as I want it presented? Basically splitting the item in a list into component parts?
Here is the code that pulls the lists: -
def get_date(datestr):
try: # py3
adate = datetime.datetime.fromtimestamp(datestr.Start.timestamp())
except Exception:
adate = datetime.datetime.fromtimestamp(int(datestr.Start))
return adate
def getCalendarEntries(days=3, dateformat="%d/%m/%Y"):
Outlook = win32com.client.Dispatch("Outlook.Application")
ns = Outlook.GetNamespace("MAPI")
appointments = ns.GetDefaultFolder(9).Items
appointments.Sort("[Start]")
appointments.IncludeRecurrences = "True"
today = datetime.datetime.today()
begin = today.date().strftime(dateformat)
tomorrow = datetime.timedelta(days=days) + today
end = tomorrow.date().strftime(dateformat)
appointments = appointments.Restrict(
"[Start] >= '" + begin + "' AND [END] <= '" + end + "'")
events = []
for a in appointments:
adate = get_date(a)
events.append(event(adate, a.Subject, a.Duration))
return events
if __name__ == "__main__":
events = getCalendarEntries()"""
Thanks all,
Graeme
This maybe a bit hacky but the syntax for event in your string is the same as one would define a dictionary. So we can replace 'event' with 'dict' and call eval which basically evaluates a string as if it was Python code. so for example if you run this
import datetime
event_str = r"event(Start=datetime.datetime(2020, 11, 30, 12, 30), Subject='meeting 1 description', Duration=60)"
dict_str = event_str.replace('event','dict')
my_dict = eval(dict_str)
print(my_dict)
this will print
{'Start': datetime.datetime(2020, 11, 30, 12, 30), 'Subject': 'meeting 1 description', 'Duration': 60}
So my_dict will be a dictionary that you can pull various bits out of, such as my_dict['Start'] will give you the start (as datetime), etc
you would need to call this construct on each element of your events list, eg the following should create a list of dictionaries, one for each event
all_dicts = [eval(e.replace('event','dict')) for e in events]
of course you can save yourself all this trouble if you created dictionaries in the first place, so replace the relevant line in your loop with
events.append(dict(Start=adate, Subject=a.Subject, Duration=a.Duration))
and then use dict functionatility to get the fields via events[i]['Start'] etc
So this is what I came up with after your suggestion - worked like a treat - thank you so much :) You are a super star!
import win32com.client
import datetime
from collections import namedtuple
event = namedtuple("event", "Start Subject Duration")
def get_date(datestr):
try: # py3
adate = datetime.datetime.fromtimestamp(datestr.Start.timestamp())
except Exception:
adate = datetime.datetime.fromtimestamp(int(datestr.Start))
return adate
def getCalendarEntries(days=3, dateformat="%d/%m/%Y"):
Outlook = win32com.client.Dispatch("Outlook.Application")
ns = Outlook.GetNamespace("MAPI")
appointments = ns.GetDefaultFolder(9).Items
appointments.Sort("[Start]")
appointments.IncludeRecurrences = "True"
today = datetime.datetime.today()
begin = today.date().strftime(dateformat)
tomorrow = datetime.timedelta(days=days) + today
end = tomorrow.date().strftime(dateformat)
appointments = appointments.Restrict(
"[Start] >= '" + begin + "' AND [END] <= '" + end + "'")
events = []
for a in appointments:
adate = get_date(a)
events.append(dict(Start=adate, Subject=a.Subject, Duration=a.Duration))
return events
if __name__ == "__main__":
events = getCalendarEntries()
print ("Time:", events[1]['Start'])
print ("Subject:",events[1]['Subject'])
print ("Duration:",events[1]['Duration'])
I have the following var: time_created = datetime.utcnow()
How to create a time_created_day var from time_created that will contain only Y, M, d
like this datetime.datetime(2017, 11, 7)
I have the following solution:
from datetime import date
time_created_day = date(time_created.year, time_created.month, time_created. day)
is it the best way?
Use datetime.utcnow().date()
datetime.utcnow().date()
datetime.date(2017, 11, 7)
Adding to answer
The datetime object always contains year, month, day as well as hours, minutes, seconds, and microseconds. It is a combination of what the date and time objects contain, see datetime Objects
from datetime import datetime
# this is your datetime object
time_created = datetime.utcnow()
# when you want to see it formatted as Y,M,D call the date method
date_created = time_created.date()
time_created
date_created
Output:
datetime.datetime(2017, 11, 7, 23, 43, 43, 761750)
datetime.date(2017, 11, 7)`
Use time_created.day to find the day.
time_created_day = time_created.day
(Similar for month and year)
here it is easiest for you
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + " " + month + " " + day;
I got this function. What I need is to make some changes in my model depending on the day. As my if statements shown below, if the "ddate" is today or tomorrow make some changes in my "pull_ins" column and set it up as "Ready to ship" but if is the day after tomorrow and the next day, set "Not yet". This is working but my problem is that I need to jump weekends and keep the 4 days logic, any ideas?
As an example if today is Thrusday to get the ddate from today, tomorrow(friday) -----jump weekend --- monday, tuesday.
This is what I got:
def Ship_status():
week = {0, 1, 2, 3, 4}
deltaday = timedelta(days=1)
today = datetime.now().date()
day = today
day1 = day + deltaday
day2 = day1 + deltaday
day3 = day2 + deltaday
for i in Report.objects.all():
if i.ddate.weekday() in week:
if i.ddate == day:
i.pull_ins = "Ready to ship"
i.save()
if i.date == day1:
i.pull_ins = "Ready to ship"
i.save()
if i.date == day2:
i.pull_ins = "Not yet"
i.save()
if i.date == day3:
i.pull_ins = "not yet"
i.save()
Thanks for your time.
dateutil.rrule is library you could leverage. To get the next weekday:
from dateutil import rrule
next_weekday = rrule.rrule(rrule.DAILY, count=3, byweekday=(0, 1, 2, 3, 4), dtstart=dt))
So, in your query, you could do something like this:
def compute_shipping(dt=datetime.datetime.date(), count=2):
next_weekdays = rrule.rrule(rrule.DAILY, count=count, byweekday=(0, 1, 2, 3, 4), dtstart=dt))
return list(next_weekdays)
#Ready to ship
Report.objects.filter(ddate__in=compute_shipping()).update(pull_ins="Ready to ship")
#For Not yet
#Query would be similar - just set the appropriate start date
I am using Python 2.7.
I want to get the next 25th day of the month from now on. Today is February 17th, so I should get February 25th. If we were on February 26th, I should get March 25th.
I was not able to find anything about getting the next specific day of the month, but I am pretty sure that Python has something to make it easy.
Does anyone know how?
You could use python-dateutil for that and play with the rrule:
import datetime
from dateutil.rrule import *
now = datetime.datetime.today().date()
days = rrule(MONTHLY, dtstart=now, bymonthday=25)
print (days[0]) # datetime.datetime(2016, 2, 25, 0, 0)
print (days[1]) # datetime.datetime(2016, 3, 25, 0, 0)
import datetime
def get_next_date_with_day(day_of_the_month):
today_date = datetime.datetime.today()
today = today_date.day
if today == day_of_the_month:
return today_date
if today < day_of_the_month:
return datetime.date(today_date.year, today_date.month, day_of_the_month)
if today > day_of_the_month:
if today_date.month == 12:
return datetime.date(today_date.year+1, 1, day_of_the_month)
return datetime.date(today_date.year, today_date.month+1, day_of_the_month)
print get_next_date_with_day(25)
>>2016-02-25
def get_25_th_day(curr_date):
if curr_date.day <= 25:
return datetime.date(curr_date.year, curr_date.month, 25)
else:
new_month = curr_date.month + 1
new_year = curr_date.year
if curr_date.month == 12:
new_month = 1
new_year = curr_date.year + 1
return datetime.date(new_year, new_month, 25)
print get_25_th_day(datetime.date.today())
>> 2016-02-25
print get_25_th_day(datetime.date(2016, 2, 25))
>> 2016-02-25
print get_25_th_day(datetime.date(2016, 2, 26))
>> 2016-03-25
print get_25_th_day(datetime.date(2016, 12, 26))
>> 2017-01-25