I defined two variables for previous days (one for friday and one for monday to thursday). After giving the condition, it asks for varible not defied, below is the code.
import datetime
d = datetime.date.today()
if d.weekday() == 0:
tdelta = datetime.timedelta(days=3)
friday = d - tdelta
else:
tdelta1 = datetime.timedelta(days=1)
prev_day = d - tdelta1
if data_date == friday:
print("Data as on", friday, "for page")
elif data_date == prev_day:
print("Data as on", prev_day, "for page")
else:
print("Data update required.")
For the above code, error is shown as 'prev_day' not defined. Please help.
Related
my first code i have written whilst learning, and have become stuck on one issue.
NAME=str(input("Enter your name: "))
print ("hello",NAME)
from datetime import *
today = date.today()
print("Today: " + today.strftime('%A %d, %b %Y'))
good_value = False
value = ""
while good_value == False:
value = input("Insert Date in format dd/mm/yyyy: ")
try:
datetime.strptime(value, '%m/%d/%Y')
good_value = True
except ValueError:
print("Error: Date format invalid.")
thisYear = today.year
dob_data = value.split("/")
dobDay = int(dob_data[0])
dobMonth = int(dob_data[1])
ÁdobYear = int(dob_data[2])
dob = date(thisYear,dobMonth,dobDay)
if today == date(thisYear,dobMonth,dobDay):
print ("happy bithday", NAME)
else:
print ("its not your birthday, sucks to be you")
when i run the code it will work perfectly unless i type the date being over the 12th, so not breaking the error loop and obviously limiting the dates that can be put into the finished product.
Here
value = input("Insert Date in format dd/mm/yyyy: ")
you are informing user that format should be DD/MM/YYYY, but here
datetime.strptime(value, '%m/%d/%Y')
you are expecting MM/DD/YYYY. In order to repair this replace former using
value = input("Insert Date in format mm/dd/yyyy: ")
and
dobDay = int(dob_data[0])
dobMonth = int(dob_data[1])
using
dobDay = int(dob_data[1])
dobMonth = int(dob_data[0])
Observe that this did worked for values equal or less than 12 as there are 12 months
I'm trying to make it so that it checks if its in the format I want and if its greater than today's date. I want it to ask for input until it gets a right answer but I can't find a way to do so.
while True:
try:
x=dt.datetime.strptime(input(), '%d/%m/%Y')
break
except ValueError:
print(1)
You can use the today class method to get a datetime object representing today's date, and use the > or < operator to compare it to the parsed x:
while True:
try:
x = dt.datetime.strptime(input(), '%d/%m/%Y')
if x > dt.datetime.today():
break
else:
print('before today')
except ValueError:
print('wrong format')
from datetime import datetime, date
while True:
input_ = input('Enter a date -> ')
try:
dt = datetime.strptime(input_, '%d/%m/%Y').date()
except ValueError:
dt = None
today = date.today()
if dt and dt > today:
break
print('All good!')
->
Enter a date -> 12/01/2021
Enter a date -> 18/01/2021
Enter a date -> 25/01/2021
Enter a date -> 14/02/2021
All good!
Customized your existing code to handle - a) Valid Date Check b) Greater than Today's Date condition.
import datetime as dt
while True:
try:
x = dt.datetime.strptime(input(), '%d/%m/%Y')
if x > dt.datetime.now():
print(x)
break
else:
print("Please Enter a Valid Date:")
except ValueError:
print("Invalid Date Format")
My solution;
import datetime as dt
todays_date = dt.datetime.now()
todays_seconds = todays_date.timestamp()
done = False
while not done:
user_input = input(f"Please type a date later that today's date ({todays_date.strftime('%d/%m/%Y')}): ")
try:
x = dt.datetime.strptime(user_input, '%d/%m/%Y')
if x.timestamp() <= todays_seconds:
print("Date must be after today's date")
else:
done = True
except ValueError:
print('Input not understood, please try again')
Gives;
Please type a date later that today's date (30/01/2021): 30/01/2021
Date must be after today's date
Please type a date later that today's date (30/01/2021): 31/01/2021
Process finished with exit code 0
My test code works for the first record with one day entered but the body of the code does not work. The code continues to run asking for the day and hours worked. I enter "done" and it doesn't accept that either.
I initially thought creating a list for the days entered but wasn't sure when to access the list to print the footer before going to the next input. There are no errors just won't execute as expected. This is an assignment and many of the declarations were already populated.
Expected Results with user input:
Day worked: Tuesday
Hours Worked: 3
Day worked: Tuesday
Hours Worked: 4
Day Total 7
Here's my code.
HEAD1 = "WEEKLY HOURS WORKED"
DAY_FOOTER = "Day Total "
SENTINEL = "done" # Named constant for sentinel value
hoursWorked = 0 # Current record hours
hoursTotal = 0 # Hours total for a day
prevDay = "" # Previous day of week
notDone = True # loop control
days=[]
# Print two blank lines.
print("\n\n")
# Print heading.
print("\t" + HEAD1)
# Print two blank lines.
print("\n\n")
# Read first record
dayOfWeek = input("Enter day of week or done to quit: ")
if dayOfWeek == SENTINEL:
notDone = False
else:
hoursWorked =int(input("Enter hours worked: "))
prevDay = dayOfWeek
hoursTotal = hoursWorked
days.append(dayOfWeek)
print("\t" + DAY_FOOTER + str(hoursTotal))
print(days)
while notDone == True:
dayOfWeek = input("Enter day of week or done to quit: ")
prevDay = dayOfWeek
hoursWorked =int(input("Enter hours worked: "))
hoursTotal = 0
hoursTotal = hoursTotal + hoursWorked
days.append(dayOfWeek)
print(days)
def dayChange(DAY_FOOTER,hoursWorked):
if dayOfWeek == dayOfWeek:
DAY_FOOTER = dayOfWeek
hoursTotal = (hoursWorked + hoursWorked)
print("\t" + DAY_FOOTER + str(hoursTotal))
days.append(dayOfWeek)
else:
print("\t" + DAY_FOOTER + str(hoursTotal))
def endOfProgram(done):
if dayOfWeek == "done":
notDone == False
return```
There are several issues with the code:
First of all, you are not really sensitive to the "done" command within the while loop. You do test the notDone variable, but you never write to this variable while inside the loop. The test should be embedded in the loop itself, and is superfluous outside it. Second of all, with each iteration of the while loop you initialize the hoursTotal variable to 0, so that you do not memorize the values from the previous days. Perhaps you should use an additional list for keeping track of hours, or use a day_of_the_week:hours dictionary.
I have a code which starts a main function. In this function have a while loop which should starts program when certain time comes. I have set this time in morning (start time), evening(end time) variables. It is in while loop and it works, but only if I start the program the day I want to use it. For example: When I start it Monday evening (20:00) and start time(morning variable) is from 8:00 (next day), it will continue loop
print("Waiting for the right time") <=(doing this)
even if that time the next day comes. But It works when I start it the next day at 6:00 or so...
Can someone explain me, why this happens?
Here is the code
import datetime
from time import sleep
from datetime import date
#variables
now = datetime.datetime.now()
morning = now.replace(hour=8, minute=0, second=0, microsecond=0)
evening = now.replace(hour=16, minute=15, second=0, microsecond=0)
#function for time-setting
def time_in_range(morning, evening, x):
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
timerange = time_in_range(morning, evening, now)
#main function
def main():
while True:
# Time period check
if date.today().weekday() < 5 and date.today().weekday() >= 0:
dayz = True
else:
dayz = False
if dayz != True:
print("Waiting for the day")
sleep(3600)
continue
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
if timerange != True: # HERE IT MAKES THE TROUBLE
print("Waiting for the right time")
sleep(200)
continue
print("do something")
main()
print("end of code")
When you call .replace() to set the morning and evening times, it keeps the current date as part of the datetime object. So if you were to call it a day before, the dates would be set to the previous day's date, and thus .now() will never be in between the previous day's time range.
E.g. if on January 1st you make the calls to set morning and evening, the stored datetimes will be "January 1st 8am" and "January 1st 4pm". The next time when your loop is checking, it asks "Is January 2nd 10am between January 1st 8am and January 1st 4pm" and of course the answer is no, because January 1st was the day before.
You probably want to use the datetime.time class instead of the datetime.datetime class, if you're only wanting to check for time. Alternatively, you could set the date portion of your evening and morning datetimes to the specific date you want to match (but that wouldn't help for repeating weekly).
import datetime
from time import sleep
from datetime import date
#variables
now = datetime.datetime.now()
morning = now.replace(hour=8, minute=0, second=0, microsecond=0)
evening = now.replace(hour=16, minute=15, second=0, microsecond=0)
#function for time-setting
def time_in_range(morning, evening, x):
# Updated code
morning = x.replace(hour=8, minute=0, second=0, microsecond=0)
evening = x.replace(hour=16, minute=15, second=0, microsecond=0)
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
timerange = time_in_range(morning, evening, now)
print(timerange)
#main function
def main():
while True:
# Time period check
if date.today().weekday() < 5 and date.today().weekday() >= 0:
dayz = True
else:
dayz = False
if dayz != True:
print("Waiting for the day")
sleep(3600)
continue
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
if timerange != True: # HERE IT MAKES THE TROUBLE
print("Waiting for the right time")
sleep(200)
continue
print("do something")
main()
print("end of code")
I need to change months from a string value to a integer value so I can perform a calculation. I am using the datetime library which can give the current date and I need to compare this to a date entered by the user to find the difference between the months in integer form.
import datetime
current_month = datetime.date.today().strftime('%B')
month_join = input('Please enter the month you joined')
month_difference = current_month - month_join
I would like the input to be as a month if possible. If not I will just use:
month_join = int(input('Please enter the month you joined')
It sounds like what you need is a dictionary which relates the name of a month and its numerical value.
import datetime
month_names = ["January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"]
months = {name : (index + 1) for index, name in enumerate(month_names)}
current_month = datetime.date.today().strftime('%B')
month_joined = input("Please enter the month you joined: ")
month_difference = abs(months[current_month] - months[month_joined])
print(month_difference)
You can also accomplish the creation of the dictionary through use of the calendar module's month_name list attribute.
import datetime, calendar
months = {name : (index + 1) for index, name in enumerate(calendar.month_name[1:])}
current_month = datetime.date.today().strftime('%B')
month_joined = input("Please enter the month you joined: ")
month_difference = abs(months[current_month] - months[month_joined])
print(month_difference)
Probably the strptime method in datetime will be of some use to you. For example:
import datetime
current_month = datetime.date.today().strftime('%B')
month_join = datetime.datetime.strptime(input('Please enter the month you joined'), "%B")
month_difference = current_month.month - month_join.month
But be careful with this - what if the user joined in the previous calendar year? You would end up with a negative value for month_difference.
You would probably be better off actually getting the full month and year the user joined, turn that into a datetime object, subtract it form datetime.today() to get a timedelta object. Then get the month count from that timedelta object.
You may as well leverage the datetime library as much as possible, rather than trying to reinvent the wheel.
This method allows the user multiple chances to enter a correct answer if they mess up the first time. It also checks to make sure that the number is a valid month. You can also add checks to see if the user needs to include the year. IE: if current_month - month_join < 0 ask them for the year.
import datetime
current_month = datetime.date.today().month
month_join = None
while month_join is None:
month_join = raw_input('Please enter the month you joined: ')
if month_join == 'quit':
exit(1)
try:
month_join = int(month_join)
if month_join > 12 or month_join < 1 or not isinstance(month_join, int):
print('Please enter a month value that is from 1 to 12')
month_join = None
except Exception as e:
if isinstance(e, TypeError) or isinstance(e, ValueError):
print('Please enter the month as an integer. IE. May = 5. If you want to close the program type "quit"')
month_join = None
else:
raise e
month_difference = current_month - month_join
print month_difference
Try the monthdelta library.
import datetime
import monthdelta
current_month = datetime.date.today()
year = current_month.year
month_in = input('Please enter the month you joined')
month_dt = datetime.datetime.strptime(month_in, '%B').date()
# Construct new datetime object with current year
month_join = datetime.date(year=year, month=month_dt.month, day=1)
# Reduce year by one if the month occurs later
if month_join > current_month:
month_join = datetime.date(year=year - 1, month=month_dt.month, day=1)
month_difference = monthdelta.monthmod(month_join, current_month)
print(month_difference[0].months)