good day! How to properly apply a FOR loop to a given function?
thanks for the tips:)
from datetime import timedelta
from apps.tickets.models import PatientConsultationTicket
def tickets_change():
tickets = PatientConsultationTicket.object.all()
one_day = tickets.created_at + timedelta(days=1)
if datetime.now() > one_day:
tickets.status = 'rd'
tickets.save()
elif datetime.now() < one_day:
tickets.status = 'e'
tickets.save()
To answer your question that's how you can iterate on the tickets :
from datetime import timedelta
from apps.tickets.models import PatientConsultationTicket
def tickets_change():
tickets = PatientConsultationTicket.objects.all()
for ticket in tickets:
one_day = ticket.created_at + timedelta(days=1)
if datetime.now() > one_day:
ticket.status = 'rd'
ticket.save()
elif datetime.now() < one_day:
ticket.status = 'e'
ticket.save()
Though, it's probably not the best way to do what you want.
Instead you should probably use an "UPDATE" query (not tested but it could look to something like that):
PatientConsultationTicket.objects.filter(created_at__gte=datetime.now()-timedelta(days=1)).update(status='rd')
PatientConsultationTicket.objects.filter(created_at__lte=datetime.now()-timedelta(days=1)).update(status='e')
Related
I tried these codes.
x = 6
while 1:
if x < 0.999:
break
#execute you function after 6 seconds.
x -= 0.01
sleep(0.01)
But i need to execute on a particular time . So i tried this:
if (self.is_hour_between("09:55:00", "11:20:00")) == True:
#your function
else:
#your function
def time_between(self, start, end):
# Time Now
now = datetime.now().time()
# Format the datetime string
time_format = "%H:%M:%S"
# Convert the start and end datetime to just time
start = datetime.strptime(start, time_format).time()
end = datetime.strptime(end, time_format).time()
is_between = False
is_between |= start <= now <= end
is_between |= end <= start and (start <= now or now <= end)
return is_between
i wanted to run the function at exactly 10 Am and 11Am .If its not the time then wait for it.else if its the time then go for it without waiting
Anwser :
import datetime
import time
while True:
current_dt = datetime.datetime.now()
time_a = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 9, 55)
time_b = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 11, 20)
if (time_a<current_dt) and (time_b > current_dt):
print('ok')
else:
time.sleep(60)
For a school project, I am writing a function that takes in a datetime variable. If the datetime_variable.day_name() != 'Friday' I need to subtract a day until the day_name is equal to Friday. I wrote what I thought was a recursive function to do this, however my loop never ends.
def getDateSplit(date_variable):
from datetime import timedelta
max_date = date_variable
print('Max Date:', max_date, 'Day of Week:', max_date.day_name())
if(max_date.day_name() == 'Friday'):
return max_date
else:
return getDateSplit(max_date - timedelta(days = 1))
The following minimally adapted version will work:
def getDateSplit(date_variable):
if date_variable.day_name() == "Friday":
return date_variable
return getDateSplit(date_variable - timedelta(days=1))
Example usage:
date_variable = pd.to_datetime("2018-01-01")
date_variable.day_name() # "Monday"
friday_before = getDateSplit(date_variable)
friday_before # Timestamp('2017-12-29 00:00:00')
friday_before.day_name() # "Friday"
For anyone that cares, I went away from recursion. Not that cool yet. Here's my solution:
def getDateSplit(date_variable):
from datetime import timedelta
max_date = date_variable
while(max_date.day_name() != 'Friday'):
print('Max Date:', max_date, 'Day of Week:', max_date.day_name())
max_date -= timedelta(days = 1)
return max_date
I am trying to program a calendar that checks how many days from now/ ago (past and present) from raw_input. I need a loop that counts the days through the current year and adds it to a variable called: Total_days and this loop has to go through each year until it hits the current date that the code ran on. The end result is that the output gives you the date you entered in a complete sentence: eg. "10/08/1700 was ___ days ago" Basically my teacher explained that the past days has to add up until it hits that certain date using a loop(loops are required. This is an assignment, i cant use any other functions like delta, but loops and datetime stuff is good!) and then for the future it has to say how many days from now until that futuristic date happens using loops. I am very stumped and i need your guys' help.
Heres what i got so far:
import datetime
input_date = raw_input("Enter in full format (mm/dd/yyyy):")
year = input_date[6:10]
yeara = int(year)
montha = int(input_date[1:2])
daya = int(input_date[4:5])
from datetime import datetime
from datetime import date
now = datetime.now()
year = now.year
month = now.month
day = now.day
def isleapYear(year):
if year % 4 == 0:
check = True
if year % 100 == 0:
check = False
if year % 400 == 0:
check = True
total_days = 0
n = 12
moNum = [0,31,28,31,30,31,30,31,31,30,31,30,31]
while n > montha:
if yeara > year:
if year == isleapYear(year):
total_days += 366
elif year != isleapYear(year):
total_days += 365
if montha == month:
break
total_days += int(moNum[n])
if n == 02:
if isleapYear(year) == True:
total_days += 1
n -= 1
ny = 365
h = total_days
if yeara > year:
if year == isleapYear(year):
total_days += 366
elif year != isleapYear(year):
total_days += 365
if yeara>year:
time = "future"
if yeara<year:
time = "past"
if yeara==year:
if montha>month:
time = "future"
if montha<month:
time = past
if montha == month:
if daya>day:
time = "future"
if daya<day:
time = "past"
if daya==day:
time = "present"
print str(h.days) + " days in the " + str(time)
Thanks for helping out! i appreciate your help :)
Must you use a loop? Else, you can build from the following:
refdatestr = "2010/08/23"
refdate = datetime.strptime(refdatestr, "%Y/%m/%d")
now = datetime.now()
difference_days = (now-refdate).days
difference_days is a datetime.timedelta object. If refdate (or refdatestr) was in the future, this would be negative.
Here is an updated code, with everything fixed:
import datetime
input_date = raw_input("Enter in full format (mm/dd/yyyy):")
year = input_date[6:10]
yeara = int(year)
montha = int(input_date[1:2])
daya = int(input_date[4:5])
from datetime import datetime
from datetime import date
now = datetime.now()
year = now.year
month = now.month
day = now.day
def isleapYear(year):
if year % 4 == 0:
check = True
if year % 100 == 0:
check = False
if year % 400 == 0:
check = True
end_date = input_date
start_date = now
delta = date(year,month,day)
delta2 = date(yeara,montha,daya)
h = delta-delta2
if yeara>year:
time = "future"
if yeara<year:
time = "past"
if yeara==year:
if montha>month:
time = "future"
if montha<month:
time = past
if montha == month:
if daya>day:
time = "future"
if daya<day:
time = "past"
if daya==day:
time = "present"
print str(h.days) + " in the " + str(time)
The most important thing that you forgot is that there are functions in datetime that will automatically find the number of days till the input...
Hope this helps!!!
Don't know how to properly describe my problem, but when I compare two datetime objects in while statement the whole program stops working.
I have a method work()
import time
import datetime
def work():
now = None
intr = 10.0
d = datetime.datetime.utcnow()
least_time = datetime.datetime.combine(datetime.datetime.today(), datetime.time(10, 10, 00))
finish = datetime.datetime.combine(datetime.datetime.today(), datetime.time(10, 10, 20))
if datetime.datetime.today().weekday() == 0:
least_time = datetime.datetime.combine(datetime.datetime.today(), datetime.time(11,10,00))
finish = datetime.datetime.combine(datetime.datetime.today(), datetime.time(11,10,20))
while d <= finish:
d = datetime.datetime.utcnow()
if intr > 1 and d >= least_time:
intr = 1
print("Interval set to 1 sec")
if now == None:
now = time.time()
if time.time() - now >= intr:
print("Work")
print("_____")
now = None
print("End")
And, if I call print() or something else before that method:
print("1")
print("2")
print("3")
work()
The program just idle and do nothing.
What happens depends on your current time zone.
The call to datetime.datetime.utcnow() gives a datetime in UTC,
whereas datetime.datetime.today() gives you current datetime for your time zone (which you machine has):
Changing:
d = datetime.datetime.utcnow()
to:
d = datetime.datetime.now()
or to:
d = datetime.datetime.today()
would fix your problem.
I have four variables:
start_hour = '12'
start_minute = '00'
end_hour = '22'
end_minute = '30'
and from datetime:
current_hour = datetime.now().hour
curren_minute = datetime.now().minute
And I want to compare if the current time is within the range:
if int(start_hour) <= current_hour and int(end_hour) >= current_hour:
something
But how to implement this with minutes?
You can use datetime.timedelta to do the comparisons reliably. You can specify a delta in different units of time (hours, minutes, seconds, etc.) Then you don't have to worry about converting to hours, minutes, etc. explicitly.
For example, to check if the current time is more than an hour from the start_time:
if abs(datetime.now() - start_time) > datetime.timedelta(hours=1):
# Do thing
You can also use timedelta to shift a time by a given amount:
six_point_five_hours_from_now = datetime.now() + datetime.timedelta(hours=6, minutes=30)
The nice thing about timedelta apart from easy conversions between units is it will automatically handle time differences that span multiple days, etc.
A much better way to go about this would beto convert both times to minutes:
start_time = int(start_hour)*60 + int(start_minute)
end_time = int(end_hour)*60 + int(end_minute)
current_time = datetime.now().hour*60 +datetime.now().minute
if start_time <= current_time and end_time >= current_time:
#doSomething
If you need to include seconds, convert everything to seconds.
What about:
>>> import datetime
>>> now = datetime.datetime.now()
>>> breakfast_time = now.replace( hour=7, minute=30, second=0, microsecond=0 )
>>> lunch_time = now.replace( hour=12, minute=30, second=0, microsecond=0 )
>>> coffee_break = now.replace( hour=16, minute=00, second=0, microsecond=0 )
>>> breakfast_time <= lunch_time <= coffee_break
True
A simple and clear way to do it all with just datetime objects is:
now = datetime.now()
start = now.replace(hour = int(start_hour), minute = int(start_minute))
end = now.replace(hour = int(end_hour), minute = int(end_minute))
if start <= now <= end:
print('something')