Issue:
My program keeps telling me, no matter what, that my date is invalid.
Assignment:
The user will input a year, a month number (1-12), and a day number in that order. The program will
determine if the date is in the future, or in the past. (If the date entered is today’s date, assume the date
is in the past). A future date is a date that has not happened yet. If today is July 31st, August 1 of the
same year is not in the past, just because the day (1) comes before today’s day (31). For the input, if the user enters an invalid month, display an appropriate error message (like “Invalid
Month”) and end the program. If the user enters an invalid day, display an appropriate error message
(like “Invalid Day”) and end the program. Assume 28 days in February. In other words, if the month is
February and the day entered is 29, display the error message and end the program.
Remember:
Thirty days has September,
April, June, and November
All the rest have 31
Except February, which has 28….
Define a function called inTheFuture() that accepts a given year number, a month number, and a
day number as 3 separate arguments. The function should return a Boolean value (True or False) to
indicate whether the date (year, month, and day) parameters are in the future or not. A True return
occurs if the date is in the future; False if the date is in the past. It should not draw any images or text to
the screen. It also should not ask the user for input. It just determines if a given date is in the future or
not.
Find an image to represent the future, and an image to represent the past. Examples could include
something like “The Jetson’s” for the future, and an old wagon for the past.If the date is in the future, display your future image in the middle of a canvas. If the date is in the past,
display your past image in the middle of the canvas. At the top of the canvas, display “In the future” or
“In the past”, whichever matches the image.
To find the current date, you may add this import and function to your code:
import datetime
def getTodaysDate():
return datetime.datetime.today()
If you call this function somewhere in your code:
today = getTodaysDate()
Then you can use the year, month, and day member variables to obtain the current year, month, and
day. For example:
print(today.month)
would output the current month.
Here is my program that I thought was finished. What am I missing?
This works for a date input like "24.12.2016". Change it to your needs in the line of strptime().
import datetime
from time import strptime
def date_in_the_future(date):
datetime_string = strptime(date, "%d.%m.%Y")
d = datetime.datetime(datetime_string[0],datetime_string[1],datetime_string[2])
now = datetime.datetime.now()
delta = d - now
diff = delta.days + 1
if diff > 0:
return True
else:
return False
You should learn how to use if,else, and elif. Check the code below:
import datetime
def getTodaysDate():
return datetime.datetime.today();
today = getTodaysDate();
print(today)
#def inTheFuture():
year= input ("Enter Year: ");
month= int(input ("Enter Month: "));
day= int(input ("Enter Day: "));
print"Correct, Your Day is:",day,"/",month,"/",year
if (month > 12):
print("How many months in a year? Not as many as you think I suppose..")
raise SystemExit
elif month in [1,3,5,7,8,10,12]:
if day > 31:
print("What is a month where you are from?")
raise SystemExit
else:
print"Correct, Your Day is:",day,"/",month,"/",year
elif (month == 2):
if (day > 28):
print("February only has so many days!")
raise SystemExit
else:
print"Correct, Your Day is:",day,"/",month,"/",year
elif (month in [4,6,9,11]):
if (day > 30):
print("That day is not possible!")
else:
print"Correct, Your Day is:",day,"/",month,"/",year
Related
I'm trying to build a list of "pay days" for a given month in the future knowing only when the pay days started months ago. For example:
Starting date - When the paychecks started: 1/6/2023
Frequency is every two weeks
So if I want to know which dates are pay days in March, I have to start at the 1/6/2023 and add two weeks until I get to March to know that the first pay day in March is 3/3/2/2023.
Then I want my final list of dates to be only those March dates of:
(3/3/2023, 3/17/2023, 3/31/2023)
I know I can use pandas to do something like:
pd.date_range(starting_date, starting_date+relativedelta(months=1), freq='14d')
but it would include every date back to 1/6/2023.
The easiest thing to do here would be to just update the starting_date parameter to be the first pay day in the month you're interested in.
To do this, you can use this function that finds the first pay day in a given month by first finding the difference between your start date and the desired month.
# month is the number of the month (1-12)
def get_first_pay_day_in_month(month=datetime.datetime.now().month,
year=datetime.datetime.now().year,
start_date=datetime.datetime(2023, 1, 6),
):
diff = datetime.datetime(year, month, 1) - start_date
freq = 14
if diff.days % freq == 0:
print(f'Difference: {diff.days/freq} weeks')
return datetime.datetime(year,month,1)
else:
print(f'Difference: {diff.days} days')
print(f'Days: {diff.days % freq} extra')
return datetime.datetime(year,month,1 + 14 - (diff.days % freq))
Then you can use this function to get the first pay day of a specific month and plug it into the date_range method.
from dateutil import relativedelta
starting_date = get_first_pay_day_in_month(month=3)
pay_days = pd.date_range(starting_date, starting_date+relativedelta.relativedelta(months=1), freq='14d')
print(pay_days)
I am new to the python language and I am writing code for a program that takes in a month as a string and a day as an int. I am up to the part where I need to check the date and I am unsure of how to go about it.
My current code for the part I am up to is this
for day in range(1,day):
if month == 'January' and day == range(32):
print('It is Winter')
The issue I am having is when it comes to the range(32) part. How do I make it so I can check the date number in a range from 1,31?
Use day in range(...) to check if day is in the given range.
Note that you probably don't want to do this in a loop. I'd suggest putting the number of days in each month in a dict so you can just look it up, e.g.:
months = {
'January': 31,
'February': 29,
'March': 31,
# ...
}
month, day = input("Month?" ), int(input("Date? "))
if month not in months:
print(f"{month} isn't a month")
elif day not in range(1, months[month] + 1):
print(f"There aren't {day} days in {month}")
The following code works but stops after 29th of Feb. The website returns "you have entered an invalid date. Please re-enter your search", which necessitate clicking on "OK". How do I get around this?
country_search("United States")
time.sleep(2)
date_select = Select(driver.find_element_by_name("dr"))
date_select.select_by_visible_text("Enter date range...") #All Dates
select_economic_news()
#btnModifySearch
for month in range(1,9):
for day in range(1,32):
try:
set_from_month(month)
set_from_date(day)
set_from_year("2020")
set_to_month(month)
set_to_date(day)
set_to_year("2020")
time.sleep(5)
#select_economic_news()
time.sleep(5)
search_now()
time.sleep(8)
export_csv()
modify_search()
time.sleep(5)
#country_remove()
except ElementClickInterceptedException:
break
logout()
If you can only use the methods featured in the initial post then I would try something like:
set_from_year('2020')
set_to_year('2020')
for month in range(1, 9):
# 1 to 9 for Jan to Aug
month_str = '0' + str(month)
set_from_month(month_str)
set_to_month(month_str)
for day in range(1, 32):
# Assuming an error is thrown for invalid days
try:
# Store data as needed
except Exception as e:
# print(e) to learn from error if needed
pass
There is a lot more that goes into this if it turns out that you're writing these methods yourself and need to loop through HTML and find a pattern for daily data.
I believe you want to dynamically obtain the number of days in a month, so that you can loop over that number to get data for each date. You can do this as follows:
from datetime import datetime
currentDay = datetime.today()
# You can set the currentDay using this if you want the data till the current date or
# whenever your scheduler runs the job.
# Now you need to get the number of days in each month from the chosen date, you can
# have the corresponding function like getStartMonth() in your program which will
# return the starting month.
from calendar import monthrange
daysPerMonth = {}
year = currentDay.year #TODO : change this to getStartYear()
startMonth = 3 # TODO : Implement getStartMonth() in your code.
for month in range(startMonth, currentDay.month+1):
# monthrange returns (weekday,number of days in that month)
daysPerMonth[month] = monthrange(year, month)[1]
for month in daysPerMonth.items():
print(month[0], '-',month[1])
This will output something like this(Number of days in a month from - March 2020 till August 2020):
3 - 31
4 - 30
5 - 31
6 - 30
7 - 31
8 - 31
And then you can run a loop for number of days while referring the range from the dict that you've obtained.
NOTE : In the function where you're running the loop to get data for each date add one if condition to check if it's the last day of the year and modify the year accordingly.
Maybe You can use these function to get count days of month:
import datetime
def get_month_days_count(year: int, month: int) -> int:
date = datetime.datetime(year, month, 1)
while (date + datetime.timedelta(days=1)).month == month:
date = date + datetime.timedelta(days=1)
return date.day
In python, How can we calculate the first day of the week when given a year and the particular week number of the year?
Note that date should be in format YYYY-MM-DD. Year and the week number is given in int format..
I am making the following assumptions about what your question means. If they are off, it should not be hard to adjust the code.
1) The first day of the week is Sunday. (so the answer is always a Sunday)
2) The week in which January 1 falls is week 1 (not 0).
Then the work breaks down into two parts.
a) Figure out the first day of the first week.
b) Add the right number of days onto that.
In Python, it looks as follows:
import datetime
def firstDayOfWeek1(y):
#takes a year and says the date of the first Sunday in the week in which January 1 falls
janDay = datetime.date(y,1,1)
while (janDay.weekday()!=6):#back up until Sunday, change if you hold Sunday is not the first day of the week
janDay=janDay-datetime.timedelta(days=1)
return janDay
def firstDayOfWeekN(y, n):#takes a year and a week number and gives the date of the first Sunday that week
return firstDayOfWeek1(y)+datetime.timedelta(weeks=(n-1))
def formattedFirstDayOfWeekN(y, n):#takes a year and a week number and gives the date of the first Sunday that week
return firstDayOfWeekN(y, n).isoformat()
#example
print formattedFirstDayOfWeekN(2018,2)#2018-01-07, first day of second week of January this year
I am using an algorithm which starts with a close-by date and then simply loops down till it finds the desired result. I am sacrificing some CPU cycles for ease of readability since the cost is not significant. I have done some limited testing but I hope the general idea is clear. Let me know your thoughts.
#This is the input in integer format
input_year = 2018
input_week = 29
#The general idea is that we will go down day by day from a reference date
#till we get the desired result.
#The loop is not computationally intensive since it will
#loop at max around 365 times.
#The program uses Python's ISO standard functions which considers Monday as
#the start of week.
ref_date = date(input_year+1,1,7) #approximation for starting point
#Reasoning behind arguments: Move to next year, January. Using 7 as day
#ensures that the calendar year has moved to the next year
#because as per ISO standard the first week starts in the week with Thursday
isoyear,isoweek,isoday = ref_date.isocalendar()
output_date = ref_date #initialize for loop
while True:
outisoyear,outisoweek,outisoday = output_date.isocalendar()
if outisoyear == input_year and outisoweek == input_week and outisoday == 1:
break
output_date = output_date + timedelta(days=-1)
print(output_date)
I tried doing it the long way by simply going down the months one by one but my teacher told me the long was was unacceptable. Now I have the day and month printed but am not sure how to quickly change the number given into the month it represents. This is what I have so far.
birthMonth = int(input("Enter your Birth Month:"))
if birthMonth <= 0 or birthMonth > 12:
print("Invalid, Choose again")
else:
birthDay = int(input("What day?:"))
if birthDay <=0 or birthDay > 31:
print('Not a valid Birthday')
else:
print(birthMonth, birthDay)
It will print the number and the day which is fine but she does not want me to list out all of the months. I would appreciate any help I can get.
You can use the datetime module to get the month associated with a number.
>>> import datetime
>>> month_num = 8
>>> month = datetime.date(2017, month_num, 1).strftime("%B")
>>> print(month)
August
Another alternative (probably the better one) is to use the calendar module
>>> import calendar
>>> month_num = 8
>>> calendar.month_name[month_num]
August
So, in your code, you can replace
print(birthMonth, birthDay)
with
print(calendar.month_name[birthMonth], birthDay)
but, make sure that you import the calendar module.