Error on datetime.datetime input - python

I have a menu, where I input a start and end-date. I get an error when I select choice 2 in below menu-item.
### Take action as per selected menu-option ###
if choice == 1: # Start with default window
print ("Starting Backtest from 2014-1-1 until 2015-12-31")
start = datetime.datetime(2014,1,1)
start = start.date()
end = datetime.datetime(2015,12,31)
end = end.date()
elif choice == 2:
## Get input ###
start = input('Enter Start date [Format: YYYY,M,D - 2014,1,23] : ')
start = datetime.datetime(start)
start = start.date()
end = input('Enter End date [Format: 2015,8,23] : ')
end = datetime.datetime(end)
end = end.date()
How is it possible that my menu-item 1 works but 2 doesn't?
The error is
TypeError: an integer is required (got type str)
Please help
Thanks

You might be getting that error because you are comparing a string to an integer. You can change between the two like so
>>> int('123')
>>> 123
>>> str(123)
>>> '123'

OK - after some scouring about, I found this question that helped me to the right answer.
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Text'
So I needed this code to get my script running smoothly. Under choice 2 you see the new code with strptime and strftime. Apparantly I need to go through strptime to get to strftime!
### Take action as per selected menu-option ###
if choice == 1: # Start with default window
print ("Starting Backtest from 2014-1-1 until 2015-12-31 (2 years)")
start = datetime.datetime(2014,1,1)
start = start.date()
end = datetime.datetime(2015,12,31)
end = end.date()
elif choice == 2:
## Get input ###
start_input = input('Enter Start date [Format: YYYY,M,D - 2014,01,23] : ')
start_dt_obj = datetime.datetime.strptime(start_input, '%Y,%m,%d')
start = datetime.datetime.strftime(start_dt_obj, '%Y,%m,%d')
end_input = input('Enter End date [Format: YYYY,M,D - 2015,08,23] : ')
end_dt_obj = datetime.datetime.strptime(end_input, '%Y,%m,%d')
end = datetime.datetime.strftime(end_dt_obj, '%Y,%m,%d')
However this makes my code run, but I would have like to keep the date as a date. The choice 2 code saves my date as a str unlike Choice 1. Hmm...

Related

my dob code wont recognize days above 12 without triggering my input error text

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

When user inputs same input twice (expected), how do I combine the input to output?

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.

Why isn't my alarm code printing the message at the end?

So I'm fairly new to Python and I am trying to write a code for a timer. My code is supposed to get the hour, minute, whether it's AM or PM, and a message that they want the program to print out when their timer is done. As of now, the program asks several questions and stores them in variables, but doesn't print out the message when it is done.
I have tried looking at each part of the code and the code is fairly simple so I don't understand why this is occurring.
# Set up variables
hour = int(input('What should the hour be? '))
minute = input('What should the minute be? ')
ampm = input('A.M. or P.M.? ')
if (ampm == 'A.M.'):
if (hour == 12):
hour = 0
else:
hour = hour
if (ampm == 'P.M.'):
if (hour == 12):
hour = hour
else:
hour = hour + 12
message = input('What should the message be? ')
import datetime
current_hour = datetime.datetime.today().strftime('%H')
current_minute = datetime.datetime.today().strftime('%M')
alarm = True
# Set up loop
while (alarm):
if (hour != datetime.datetime.today().strftime('%H')):
alarm = True
else:
if (minute == datetime.datetime.today().strftime('%M')):
print(message)
alarm = False
else:
alarm = True
It is supposed to print out the message that the user inputted. It's not doing that.
The variable of hour returns an int value and datetime.datetime.today().strftime('%H') returns string so your program get in the infinite loop.Change condition like
if (hour != int((datetime.datetime.today().strftime('%H')))):

How to call another script in one script, and run them at the same time?

I am very new to Python, but the project I am working on confused me.
In the project, I give multiple choices for uses to choose, one of the choices has a reminder function. So in the reminder function, the user can set reminder, and the function will match the reminder to current time every 15 seconds until they match and print a statement.
This is the code for reminder.
import time
def setReminder(number):
reminderList = []
for i in range(number):
reminderL = []
mon = input('enter the month(1-12):')
day = input('enter the date(1-31):')
hour = input('enter the hour(0-23):')
minute = input('enter the minute(0-59):')
print()
if ((int(mon)<1 or int(mon)>12)
or (int(day)<1 or int(day)>31)
or (int(hour)<0 or int(hour)>23)
or (int(minute)<0 or int(minute)>59)):
print('invalid date and time, please set again!')
mon = input('enter the month(1-12):')
day = input('enter the date(1-31):')
hour = input('enter the hour(0-23):')
minute = input('enter the minute(0-59):')
reminderL.extend((mon, day, hour, minute))
reminder = ''
for element in reminderL:
if int(element)<10:
element = '0' + element
reminder = reminder + element + ' '
reminderList.append(reminder)
return reminderList
def main():
num = int(input('enter the numbers of reminder you want to set(1-9):'))
if num not in range(1,10):
print('invalid input, try again!')
num = int(input('enter the numbers of reminder you want to set(0-9):'))
List = setReminder(num)
print(List)
for i in range(num):
tim = time.strftime('%m %d %H %M ')
while tim not in List:
time.sleep(15)
tim = time.strftime('%m %d %H %M ')
print('Hello, it is time to take medicine!')
main()
However, if the user set the reminder time to very late, for example next day, then this function will run until next day. Hence I want my body script to run while this reminder function is running.
This is generally how my body script is like(it is in a different script with the reminder one):
menu()
option = int(input('Your choice?'))
while (option != 4):
if option not in (1, 2, 3, 4):
print('Invalid input! Please select again!')
option = int(input('Your choice?'))
else:
if option == 1:
print()
elif option == 2:
feedback(gender, dat)
elif option == 3:
print()
print()
print('Anything else?')
menu()
option = int(input('Your choice?'))
So option 3 is the reminder, but while reminder function is try to match the time, I want the user to be able to use the other choices. The only way I think can work is to call the function and run it on another shell page. Could you give me any advice on how to do so?
The tool you need is threading. Suppose you have two separate script files: reminder.py and program.py. Then you have to delete or comment out line main() in reminder and import reminder and threading into program. Next is to modify program:
elif option == 3:
rem_thread = threading.Thread(
target=reminder.main)
rem_thread.start()
This is very basic example of how to use threads in Python. However, this addition to the code cannot solve your problem because of two reasons: (1) interference between input() calls in different threads; (2) blocking by input(). To solve the first problem you should pause main thread while user enters time parts. To solve the second problem you should start one more thread.
Here is the code that kinda works (Win10 / command prompt). There is a whole bunch of design issues to be addressed to make the code more or less usable. I tested it with 1 remainder because every remainder needs separate thread. Interference between input() and print() still present because several threads share the same console. This issue can be solved with processes instead of threads or with GUI. Of course, GUI is preferable.
import queue
import threading
import time
def setReminder(number):
reminderList = []
for i in range(number):
reminderL = []
mon = input('enter the month(1-12):')
day = input('enter the date(1-31):')
hour = input('enter the hour(0-23):')
minute = input('enter the minute(0-59):')
print()
if ((int(mon)<1 or int(mon)>12)
or (int(day)<1 or int(day)>31)
or (int(hour)<0 or int(hour)>23)
or (int(minute)<0 or int(minute)>59)):
print('invalid date and time, please set again!')
mon = input('enter the month(1-12):')
day = input('enter the date(1-31):')
hour = input('enter the hour(0-23):')
minute = input('enter the minute(0-59):')
reminderL.extend((mon, day, hour, minute))
reminder = ''
for element in reminderL:
if int(element)<10:
element = '0' + element
reminder = reminder + element + ' '
reminderList.append(reminder)
return reminderList
def reminder_main(wait_queue):
num = int(input('enter the numbers of reminder you want to set(1-9):'))
if num not in range(1,10):
print('invalid input, try again!')
num = int(input('enter the numbers of reminder you want to set(0-9):'))
List = setReminder(num)
print(List)
wait_queue.put('go-go-go') # unpause main thread
for i in range(num):
tim = time.strftime('%m %d %H %M ')
while tim not in List:
time.sleep(1)
tim = time.strftime('%m %d %H %M ')
print('Hello, it is time to take medicine!')
def main():
while True:
try:
option = int(input('Your choice? '))
except ValueError:
print('Cannot convert your choice into integer.')
else:
if option not in (1, 2, 3, 4):
print('Allowed options are 1, 2, 3, 4.')
else:
if option == 1:
pass
if option == 2:
pass
if option == 3:
wait_queue = queue.Queue()
# remainder thread
threading.Thread(
target=reminder_main,
kwargs={'wait_queue': wait_queue},
daemon=True).start()
wait_queue.get() # this is pause - waitng for any data
elif option == 4:
print('Exiting...')
break
if __name__ == '__main__':
# main thread
threading.Thread(
target=main).start()

Checking if inputted strings are equal to strings in list?

I'm working on a project that involves building a simplified version of a calendar agent that asks the user for when they want to schedule an appointment and does it for them (if that slot is free). This is the code I have so far:
def find_index(val, seq):
for index in range(len(seq)):
place = seq[index]
if place == val:
return index
else:
return int("-1")
def find_val(val, seq):
for ele in seq:
if val == ele:
return True
else:
return False
def init_nested_list(size_outer, size_inner):
cal = []
for outer_index in range(size_outer):
nested_list = []
for inner_index in range(size_inner):
nested_list.append("-")
cal.append(nested_list)
return cal
def get_input(possible_vals, day_or_time_string):
count = 0
if day_or_time_string == "day":
answer = input("What day would you like your appointment? ")
else:
answer = input("What time would you like your appointment? ")
answer = answer.strip()
nested_list = find_val(answer, possible_vals)
while answer in possible_vals:
break
else:
count = count + 1
answer = input("Invalid entry. Please enter a valid day: ")
if count == 3:
print("This is getting silly - still not a valid entry")
answer = input("Please do try to enter a valid day: ")
count = 0
return answer
def book_slot(cal,days_labels, times_labels, day, time): **ignore this function, haven't finished it yet**
find_index(day, days_labels)
def start_scheduler(cal, days_labels, times_labels):
while True:
day = get_input(days_labels, "day")
time = get_input(times_labels, "time")
book_slot( cal, days_labels, times_labels, day, time)
print("--------------------------------- ")
res = input("Did you want to book more appointments (type n for no, any other key for yes)? ")
if res == "n":
break
days_labels= ["Monday","Tuesday","Wednesday","Thursday", "Friday"]
times_labels = ["9","10","11","12","1","2","3","4","5"]
calendar = init_nested_list(len(days_labels), len(times_labels))
print("Welcome to the acupuncture booking system. ")
start_scheduler(calendar, days_labels, times_labels)
This is what the complete output should look like so far:
Welcome to the acupuncture booking system.
What day would you like your appointment? saturday
Invalid entry. Please enter a valid day: Monday
What time would you like your appointment? 24
Invalid entry. Please enter a valid time: 9
---------------------------------
Did you want to book more appointments (type n for no, any other key for yes)?
However, it seems that no matter what I input when the function asks me for the date/time of the appointment, it doesn't check to see if the inputted strings are equivalent to any of the acceptable ones (in the lists days_labels and times labels). Instead it just accepts any second random input to be correct as shown:
Welcome to the acupuncture booking system.
What day would you like your appointment? s
Invalid entry. Please enter a valid day: z
What time would you like your appointment? d
Invalid entry. Please enter a valid day: f
---------------------------------
Did you want to book more appointments (type n for no, any other key for yes)?
What needs to be done in order to have the function check to see if the inputted strings correspond with any of the strings in the days_labels and times_labels lists in order for the user to "book" an appointment?
So you wont to create a function to check if any inputted string have been already used.
There reason your code isnt working correctly is because you tried to check wherethere your counter is up to 3, while it isnt any loop, and thus it only ascends to 1.
To re-arrange that to a correct way for example, you would do this:
while answer not in possible_values:
<your code here>
I didn't test this at all but it should be enough to guide you to fix your incrementing error.
def isValidDayInput(input):
accept = false
# your code here
return accept
def dayInput(count, maxAttempts):
waiting = true
while (waiting && count <= maxAttempts):
answer = promptForInput()
if (isValidDayInput(answer)): # accept returned true during validation
waiting = false # answer is valid so jump out loop
else(): # accept returned false during validation
count += 1
if (!waiting && count == maxAttempts):
print("Too many incorrect attempts. Exit")
else:
print("thank you")

Categories