What exactly I am trying to do here is when Tomorrow comes (00:00) it should print Yes
import datetime
from datetime import date
r = True
rr = True
while r:
Today_Date = date.today()
while rr:
Tomorrow_Date = datetime.date.today() + datetime.timedelta(days=1)
if Today_Date == Tomorrow_Date:
print("Yes")
The way you have it now, your rr while loop will continually run and update Tomorrow_Date, and when the day rolls over, it will update before it has a chance to be compared to Today_Date. You should set both Today_Date and Tomorrow_Date outside that loop, and only update them when the dates change.
This should do the trick:
If you want two loops for other reasons:
import datetime
r = True
while r:
rr = True
Tomorrow_Date = datetime.date.today() + datetime.timedelta(days=1)
while rr:
if datetime.date.today() >= Tomorrow_Date:
print("Yes")
rr = False
Or as a single loop:
import datetime
r = True
Tomorrow_Date = datetime.date.today() + datetime.timedelta(days=1)
while r:
if datetime.date.today() >= Tomorrow_Date:
print("Yes")
Tomorrow_Date = datetime.date.today() + datetime.timedelta(days=1)
It might be a good idea to add a time.sleep() in to slow down the loops, depending on how accurate you need to be also.
Related
It works if I type if int(hour) >= 19: but I would like it to work with something similar to this line if current_time >= exit_time:
import time
current_time = time.strftime('%H:%M:%S')
exit_time = ('19:00:00','%H:%M:%S')
hour = time.strftime('%H')
minute = time.strftime('%M')
second = time.strftime('%S')
if current_time >= exit_time:
print ("It's time to go home")
else:
print ("{} hours, {} minutes and {} seconds to go home".format(18-int(hour),
59-int(minute), 59-int(second)))
Notice that you're comparing current_time (which is a string) and exit_time (which is a tuple containing 2 strings).
Maybe try something like:
if current_time >= exit_time[0]:
# your code
Since the first member of the tuple is probably what you want to compare to current_time.
Hope this helps!
The best alternative to this is.
from datetime import datetime
current_time = datetime.now().replace(microsecond=00)
exit_time = current_time.replace(hour=19, minute=00, second=00, microsecond=00)
if current_time >= exit_time:
print ("It's time to go home")
else:
time_delta = (exit_time - current_time).total_seconds()
hours_left = int(time_delta // 60 // 60)
minutes_left = int(time_delta // 60) - hours_left*60
seconds_left = int(time_delta) - hours_left*3600 - minutes_left*60
print ("{} hours, {} minutes and {} seconds to go home".format(hours_left,
minutes_left, seconds_left))
When I use SonarLint to check code, it notifies Critical that Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain.
I use a lot of if else statement, but can not use switch case.
This is my code:
str_time = str_time.lower()
if (bool(re.search(r'\d', str_time)) == True) and ('tối' or 'chiều' in str_time):
day = re.findall(r'\d+', str_time)[0]
if int(day) < datetime.date.today().day:
month = datetime.date.today().month + 1
else:
month = datetime.date.today().month
year = datetime.date.today().year
day = f'{year}-{month}-{day}'
return format_datetime(day)
elif 'hôm nay' in str_time or 'hn' in str_time or 'chiều nay' in str_time or 'tối nay' in str_time:
return format_datetime(datetime.date.today())
elif 'ngày mai' in str_time or 'mai' in str_time:
day = datetime.date.today() + datetime.timedelta(days=1)
elif 'ngày mốt' in str_time or 'mốt' in str_time:
day = datetime.date.today() + datetime.timedelta(days=2)
elif 'thứ 2 tuần sau' in str_time:
num = 7 - datetime.date.today().weekday() + 0
day = datetime.date.today() + datetime.timedelta(days=num)
elif 'thứ 3 tuần sau' in str_time:
num = 7 - datetime.date.today().weekday() + 1
day = datetime.date.today() + datetime.timedelta(days=num)
Sonar lint is right. It seems your code complexity is high. You should create smaller methods or change the logic. But if that is not possible, just ignore the linter.
I want to find out the charging duration between when the loop finds its first value of '1' and the last value of '1' it detects. I figured out how to find out the duration between 2 timings, but i am unsure of where i can put the 'timestamp' variable.
Here is my current code
from datetime import datetime
#Duration loop
date_format_str = '%H:%M:%S %p'
foundEnd = False
for i in range(len(dfDur01Mar22)):
#only display bus 'SG3079S'
if dfDur01Mar22.iloc[i,1] == 'SG3079S':
#print 'end' when first '0' appears
if not foundEnd and dfDur01Mar22.iloc[i,2] == 0:
print('end')
foundEnd = True
#prints the first time its 0
timestamp = dfDur01Mar22.DateTime[i]
#print(timestamp + " first")
#if charging type is 1
elif dfDur01Mar22.iloc[i,2] == 1:
print(dfDur01Mar22.iloc[i,0],dfDur01Mar22.iloc[i,1],dfDur01Mar22.iloc[i,2])
foundEnd = False
timestamp_2 = dfDur01Mar22.DateTime[i]
#print(timestamp_2 + "last")
#Duration between the first '1' and the last '1' detected
given_time = datetime.strptime(timestamp, date_format_str)
given_time2 = datetime.strptime(timestamp_2, date_format_str)
total = given_time2 - given_time
#print(total)
and here is the values that i need to find the duration from
You need 2 variables like start_time , end_time . after your loop you can calculate this duration.
So new concept of your code is like below .
FOUND_1_SITUATION is your '1' condition in your loop.
from datetime import datetime
#Duration loop
date_format_str = '%H:%M:%S %p'
foundEnd = False
start_time = False
end_time = False
for i in range(len(dfDur01Mar22)):
if FOUND_1_SITUATION and not start_time:
start_time = dfDur01Mar22.DateTime[i]
else :
end_time = dfDur01Mar22.DateTime[i]
duration_between_start_end = end_time - start_time
It means whenever your loop is on '1' condition start_time will be initialized once. in other conditions end_time will be updated till end of loop.
After all , you can put duration_between_start_end calculation below your loop.
Below code gives error as 'friday' no defined. If anything is missing, please help me with the same. Also if I interchange the position of 'friday' and 'prev_day' variables with if else, i get the error message with 'prev_day' not defined.
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import datetime
d = datetime.date.today()
if d.weekday() == 0:
tdelta = datetime.timedelta(days=3)
friday = d - tdelta
elif d.weekday() in range(1,5):
tdelta1 = datetime.timedelta(days=1)
prev_day = d - tdelta1
class ClassName(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path="C:\\Users\sameerj\IdeaProjects\chromedriver.exe")
def test_as_on_date(self):
driver = self.driver
driver.maximize_window()
driver.get("website")
login = driver.find_element_by_id("Email")
login.send_keys("email")
password = driver.find_element_by_id("Password")
password.send_keys("password")
password.send_keys(Keys.ENTER)
driver.find_element_by_id("menu_name").click()
driver.find_element_by_partial_link_text("page name").click()
date = driver.find_element_by_id("lblAsOn").text
new = datetime.datetime.strptime(date,'%m/%d/%Y')
data_date = new.date()
if data_date == friday:
print("Data as on", friday, "for page name")
elif data_date == prev_day:
print("Data as on", prev_day, "for page name")
else:
print("Data update required.")
driver.close()
if __name__ == '__main__':
unittest.main()
Its a common type of mistake
let me break it down your mistake
if d.weekday() == 0:
tdelta = datetime.timedelta(days=3)
friday = d - tdelta
elif d.weekday() in range(1,5):
tdelta1 = datetime.timedelta(days=1)
prev_day = d - tdelta1
if we execute your program
if d.weekday() == 0 holds false
then it will go to
elif d.weekday() in range(1,5):
but your friday = d - tdelta is in if condition. that's why its shows error
to solve that you must define friday outside if condition and reassign value in your if condition
you can solve it like this
friday = None
prev_day = None
d = datetime.date.today()
if d.weekday() == 0:
tdelta = datetime.timedelta(days=3)
friday = d - tdelta
elif d.weekday() in range(1,5):
tdelta1 = datetime.timedelta(days=1)
prev_day = d - tdelta1
new = datetime.datetime.strptime(date,'%m/%d/%Y')
data_date = new.strftime("%A")
This will give you the name of the day (Eg: Friday), then you can compare as you are doing,
if data_date == "Friday":
print("Data as on",data_date , "for page name")
And for previous days comparison, you have to do,
tdelta1 = datetime.timedelta(days=1)
prev_day = (new - tdelta1).strftime("%A")
before doing,
elif data_date == prev_day:
print("Data as on", prev_day, "for page name")
When you replaced Friday with prev_day, you are getting the error because of python interpreter is finding that variable first which is not defined.
You better write:
d = datetime.date.today()
if d.weekday() == 0:
tdelta = datetime.timedelta(days=3)
prev_day = None
friday = d - tdelta
elif d.weekday() in range(1, 5):
tdelta1 = datetime.timedelta(days=1)
prev_day = d - tdelta1
friday = None
And my suggestion for you is to use Python IDEs, they highlight such errors.
Also I believe this checks could be done using the calendar module
my_event = Event.objects.get(id=4)
current_time = datetime.datetime.now()
How do I do check if my current time is between them?
my_event.start_time < current_time < my_event.end_time
Your answer is the way to go as long as start_time and end_time don't have an associated tzinfo class. You can't directly compare a naive datetime with a timezoned-datetime.
you can use a simple if comparing three dates, like this
if date1 < yourdate < date2:
...do something...
else:
...do ...
I know old, but since this is so high on Google results, answers here don't take into consideration two cases:
If your time equals either of your range, ie your range is 6-8 and it is 6.
If your time range is say 18:00 to 6:00, valid range; however 19:00 would not match.
I wrote a function to take care of time comparison, hope this helps anyone viewing this old question.
def process_time(intime, start, end):
if start <= intime <= end:
return True
elif start > end:
end_day = time(hour=23, minute=59, second=59, microsecond=999999)
if start <= intime <= end_day:
return True
elif intime <= end:
return True
return False
The datetimes getting tested need to all naive (no timezone) or all aware (timezone). An exception should occur if you try to compare aware and naive. If all the datetimes are aware the timezones don't actually have to match that appears to be taken into consideration when comparing.
e.g.
class RND(datetime.tzinfo):
""" Random timezone UTC -3 """
def utcoffset(self, dt):
return datetime.timedelta(hours=-3)
def tzname(self, dt):
return "RND"
def dst(self, dt):
return datetime.timedelta(hours=0)
april_fools = datetime.datetime(year=2017, month=4, day=1, hour=12, tzinfo=pytz.UTC)
random_dt = datetime.datetime(year=2017, month=4, day=1, hour=9, tzinfo=RND())
random_dt == april_fools
# True as the same time when converted back to utc.
# Between test of 3 naive datetimes
start_spring = datetime.datetime(year=2018, month=3, day=20)
end_spring = datetime.datetime(year=2018, month=6, day=21)
april_fools = datetime.datetime(year=2018, month=4, day=1)
if start_spring < april_fools < end_spring:
print "April fools is in spring"
This is my script of checking the time between two different timeslots. One for morning and one for evening. This is the extended script using #Clifford's script
def Strategy_Entry_Time_Check():
current_time = datetime.datetime.now()
#current_time = current_time.replace(hour=13, minute=29, second=00, microsecond=00) #For testing, edit the time
morning_start = current_time.replace(hour=9, minute=30, second=00, microsecond=00)
morning_end = current_time.replace(hour=11, minute=00, second=00, microsecond=00)
evening_start = current_time.replace(hour=13, minute=00, second=00, microsecond=00)
evening_end = current_time.replace(hour=15, minute=00, second=00, microsecond=00)
if morning_start <= current_time <= morning_end:
print("Morning Entry")
return True
elif evening_start <= current_time <= evening_end:
print("Evening Entry")
return True
print("No Entry")
return False