This is probably very simple, but I am a beginner in python and I wanted to compare birthday dates by prompting a user to enter a date in MM-DD format. No year because year is current year (2011). It will then prompt the user to enter another date, and then the program compares it to see which one is first. Then it prints out the earlier day and it's weekday name.
Example: 02-10 is earlier than 03-11.
02-10 is on thursday and 03-11 is on friday
I just started learned modules and I know i'm supposed to use the datetime module, a date class and strftime to get the weekday name. I don't really know how to put it all together.
If someone can help me get started that would really help! I have some bits and pieces together:
import datetime
def getDate():
while true:
birthday1 = raw_input("Please enter your birthday (MM-DD): ")
try:
userInput = datetime.date.strftime(birthday1, "%m-%d")
except:
print "Please enter a date"
return userInput
birthday2 = raw_input("Please enter another date (MM-DD): ")
if birthday1 > birthday2:
print "birthday1 is older"
elif birthday1 < birthday2:
print "birthday2 is older"
else:
print "same age"
There are a few problems I can see in the code you've posted. I hope it will be helpful to point some of these out, and provide a somewhat rewritten version:
Indentation is broken, but I guess this might just be problems pasting it into Stack Overflow
strftime is for formatting times, not parsing them. You want strptime instead.
In Python, True has a capital T.
You're defining the getDate function but never using it.
You would never exit your while loop, since you don't break after getting the input successfully.
It's considered bad style to use "camel case" for variable and method names in Python.
You use the word "older" in reference to the dates, but without a year you can't say if one person is older than the other.
You catch any exception thrown when you try to parse the date, but don't display it or check its type. That's a bad idea since if you've mistyped a variable name (or some similar typo) on that line, you won't see the error.
Here's a rewritten version of your code that fixes those problems - I hope it's clear from the above why I made those changes:
import datetime
def get_date(prompt):
while True:
user_input = raw_input(prompt)
try:
user_date = datetime.datetime.strptime(user_input, "%m-%d")
break
except Exception as e:
print "There was an error:", e
print "Please enter a date"
return user_date.date()
birthday = get_date("Please enter your birthday (MM-DD): ")
another_date = get_date("Please enter another date (MM-DD): ")
if birthday > another_date:
print "The birthday is after the other date"
elif birthday < another_date:
print "The birthday is before the other date"
else:
print "Both dates are the same"
There are two main functions that are used for converting between a date object and a string: strftime and strptime.
strftime is used for formatting. It returns a string object.
strptime is used for parsing. It returns a datetime object.
More info in the docs.
Since what you want is a datetime object, you would want to use strptime. You can use it as follows:
>>> datetime.datetime.strptime('01-23', '%m-%d')
datetime.datetime(1900, 1, 23, 0, 0)
Note that not having the year being parsed will set the default to 1900.
Well, datetime.date.strftime requires datetime object instead of string.
In your case the best thing is to create date manually:
import datetime
...
birthday1 = raw_input("Please enter your birthday (MM-DD): ")
try:
month, day = birthday1.split('-')
date1 = datetime.date(2011, int(month), int(day))
except ValueError as e:
# except clause
# the same with date2
And then when you have two dates, date1 and date2, you can just do:
if d1 < d2:
# do things to d1, it's earlier
else:
# do things to d2, it'2 not later
Related
Trying to create an input validation for a date in format YYYY-MM-DD. I have two methods of doing this.
The first method seems to work, and loops back through to get input each time an error is raised.
The function in the second method is causing an infinite loop, but a nearly identical function in the first method does not.
If I enter a correctly formatted date in the second method, it prints as expected, but for any other input, it creates the infinite loop.
I'm not sure where this is breaking down?
I've looks in a number of Google results, and there are lots of date validations out there, but I haven't found one that explicitly addresses how to loop back around and try again.
I wasn't sure what else to try without essentially just rewriting method one.
import datetime as dt
#METHOD 1 - This is the first method for validating date input, which takes in individual blocks and validates each one individually.
def get_date(year_prompt, month_prompt, day_prompt):
#Year Input
while True:
try:
year = int(input(year_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if year in range(2000,3000,1):
break
else:
print("Sorry, your response must be in YYYY format and later than the year 2000.\n")
continue
#Month Input
while True:
try:
month = int(input(month_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if month in range(1,13,1):
break
else:
print("Sorry, needs to be MM and between 1-12\n")
continue
#Day Input
while True:
try:
day = int(input(day_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if day in range(1,32,1):
break
else:
print("Sorry, needs to be DD and between 1-31\n")
continue
#Takes the three inputs and puts them together into a date
date = dt.datetime(year, month, day)
#Returns the date
return date
#Runs the first method of getting and validating a date.
date = get_date("\nYYYY: ", "\nMM: ", "\nDD: ")
#Prints the validated date.
print("\nThe date you entered is: ", date, "\n")
#METHOD 2 - This is the second method for validating date, which takes in the whole date in one input, and attempts to validate it against the YYYY-MM-DD format.
def input_validation(date):
while True:
try:
dt.datetime.strptime(date, '%Y-%m-%d')
break
except ValueError:
print("\nSorry, this does not appear to be a valid date in format YYYY-MM-DD")
continue
return date
#Prints the validated date.
print("\nThe date you entered is: ", input_validation(input("Enter a date in format YYYY-MM-DD: ")), "\n")
My expected result for the second method, is either a date in format YYYY-MM-DD, or an error message that then asks for the input again.
You can get rid of the infinite loop while True, and return True or False based on the date being in the correct format
def input_validation(date):
#Flag to check date format
flag = False
try:
#If date is of correct format, set flag to True
dt.datetime.strptime(date, '%Y-%m-%d')
flag = True
except ValueError:
print("\nSorry, this does not appear to be a valid date in format YYYY-MM-DD")
#Return flag
return flag
print(input_validation('2019-01-31'))
print(input_validation('2019-001-31'))
print(input_validation('2019-01-311'))
The output will be
True
Sorry, this does not appear to be a valid date in format YYYY-MM-DD
False
Sorry, this does not appear to be a valid date in format YYYY-MM-DD
False
You can wrap this function around your while True to continue taking input from user
while True:
date_str = input('Enter Date')
if input_validation(date_str):
break
Comparing the current time with a user input time WITHOUT the date
So I'm making a lighting routine and I need to do some time comparisons to see if I'm in the middle of a cycle or out of a cycle. Long story short, I'm having issues comparing a user input of time with the formatted time of the datetime module:
def userInput():
try:
a = datetime.datetime.strptime(input('When you would like to routine to start in HH:MM 24 hour format: '), "%H:%M")
print (a.strftime("%H:%M"))
except:
print ("Please enter correct time in HHMM format")
return a
def timeComparator(a):
now = datetime.datetime.now().time()
#this obtains the current time
today = a
#if statement compares input from
print("the time now is: ", now)
if (now < today):
print ("hello human")
elif (now > today):
print ("hello plant")
if __name__=="__main__":
a = userInput()
timeComparator(a)
I'm getting the error "TypeError: '<' not supported between instances of 'datetime.time' and 'datetime.datetime'" which I guess means the formatting for comparing isn't compatible.
I DON'T need the date or anything else, just the current time. I'd like to just be able to compare if a user input time is before or after the current time.
Your today in the function timeComparator is a datetime object while your now is a time object. Just make sure your user_input returns a time object:
def userInput():
try:
a = datetime.datetime.strptime(input('When you would like to routine to start in HH:MM 24 hour format: '), "%H:%M").time() #<----- added .time()
print (a.strftime("%H:%M"))
except:
print ("Please enter correct time in HHMM format")
return a
When I run this program, i get the error, ValueError: invalid literal for int() with base 10: '', I feel like it's to do with the int and str conversions but I'm really not too sure, any help appreciated :)
CalendarDict = {1:"January", 2:"February", 3:"March", 4:"April", 5:"May",
6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"Novemeber",
12:"December"}
InputError = True
while InputError:
try:
BirthDate = str(input("Enter Birth Date in format DDMMYY - "))
except ValueError:
print("Error - Numbers in format DDMMYY only")
InputError = False
DD = BirthDate[0:2]
MM = BirthDate[3:4]
YY = BirthDate[4:6]
if MM == BirthDate[3:4]:
print("Your Birth Month is - ", (CalendarDict[int(MM)]))
I would rather put this in a comment but don't have enough reps, so here goes.
Firstly, array slicing in Python requires you to give the numbers in a format [a:b], where a is the index of the first character you want to get and b is the index of the character upto but NOT including which you want to get your characters, so variable MM should be BirthDate[2:4].
Next, to check whether something qualifies your "DDMMYY" requirement, you should probably be using int(input("Enter your DOB)) because anyone can enter random text and get away with it if you use the str() function to convert it into a string (because I believe you are looking for integral input)
Also, as mentioned in one of the comments, try putting InputError=False in the try part instead of the except part.
So code will look like this:
CalendarDict = {1:"January", 2:"February", 3:"March", 4:"April", 5:"May",
6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"Novemeber",
12:"December"}
InputError = True
while InputError:
try:
BirthDate = int(input("Enter Birth Date in format DDMMYY - ")) # change to int() from str()
InputError = False # set error to false since the above line got evaluated
except ValueError:
print("Error - Numbers in format DDMMYY only")
DD = BirthDate[0:2]
MM = BirthDate[2:4]
YY = BirthDate[4:6]
print("Your Birth Month is - ", (CalendarDict[MM])) # converting into integer is not required since it already is one!
You can use the datetime module to do what you want quite efficiently.
import datetime
while True:
try:
birthDate = datetime.datetime.strptime(input("Enter Birth Date in format DD/MM/YYYY - "), "%d/%m/%Y")
break
except ValueError as ve:
print(ve)
continue
print("Your Birth Month is - {}".format(birthDate.strftime("%B")))
This results in the usage of:
Enter Birth Date in format DD/MM/YYYY - 31/10/2000
Your Birth Month is - October
datetime is quite powerful, especially the provided .strptime, for parsing dates, and .strftime for providing various outputs. I'd advise you to read the documentation if you plan on working with input, output and dates. datetime is easily extensible to more complex tasks with dates.
If you're using Python2, change input to raw_input.
I've also removed your if statement - it seemed to be checking MM against the definition of MM. Note that CalendarDict is unecessary as you can use the power of datetime. I've changed your while loop to just use control flow statement, rather than a variable.
Also a general tip: use camelCasing or underscore_casing for variables, as CapitalCasing is generally reserved for classes.
The bit that was tripping you up was the slice notation, as noted by others. Here's a version that seems to do what you want:
CalendarDict = {1:"January", 2:"February", 3:"March", 4:"April", 5:"May",
6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"Novemeber",
12:"December"}
while True:
try:
BirthDate = str(input("Enter Birth Date in format DDMMYY - "))
break
except ValueError:
print("Error - Numbers in format DDMMYY only")
DD = BirthDate[0:2]
MM = BirthDate[2:4]
YY = BirthDate[4:]
print("Your Birth Month is - ", (CalendarDict[int(MM)]))
Note how the start and end positions match up.
I've looked all over stack overflow and so I really need help. I'm making a program that is supposed to calculate the age of a person by asking for their birth year, validating their birth year is correct, as in a whole number, and not words or any other invalid types of answers. And then subtracting the birth year from our current year. I'm having trouble with the inputting our current year and subtracting the user input birth year from it.
# Function Boolean is_valid_integer(String input_string)
# Declare Boolean is_valid
#
# is_valid = is input_string a valid integer?
# Return is_valid
# End Function
def is_valid_integer(input_string):
try:
val = int(input_string)
is_valid = True
except ValueError:
is_valid = False
return is_valid
# Function Integer get_year_born()
# Declare Boolean is_valid
#
# Display "What year were you born in? "
# Input input_string
# Set is_valid = is_valid_integer(input_string)
# While Not is_valid
# Display "Please only enter whole years."
# Input input_string
# is_valid = is_valid_integer(input_string)
# End While
# input_integer = int(input_string)
# Return input_integer
# End Function
def get_year_born():
input_string = input("What year were you born in? ")
is_valid = is_valid_integer(input_string)
while not is_valid:
input_string = input("Please only enter whole years. ")
is_valid = is_valid_integer(input_string)
input_integer = int(input_string)
return input_integer
# Function Integer calculate_difference()
# difference = 2017 - input_integer
# End Function
import datetime
def calculate_difference(difference):
difference = 2017 - input_integer
return difference
# Module calculate_age_year()
# Set born = get_year_born()
# Call calculate_difference()
# End Module
def calculate_difference():
print("Your age is: ", difference)
calculate_age_year()
After trying to import datatime into my coding, it didn't work well. I was also not looking to calculate specific days and/or time, and so I removed those part of the suggested coding, maybe that had something to do with it?
My purpose for this program is really to just calculate years, so if I'm born in 2000, I'd like the program to calculate from 2017, meaning I'd be 17 years old as of right now.
My first function is the loop to void out false inputs, the second function is to get the year the user was born in, the third function is supposed to be calculating the difference between the current date and the user's birth date, and the fourth function outputting the user's actual age.
To work with the dates in Python, you can use the module datetime.
To validate the error, a pythonic way of doing would be to use try...catch to convert the user input to a date time. Catch the possible errors and do your error management from there.
Here is a simple example:
import datetime
def print_age():
year = raw_input('Enter your age (YYYY/MM/DD): ')
try:
year = [int(i) for i in year.split('/')]
birth_data = datetime.date(year[0], year[1], year[2])
today = datetime.date.today()
time_diff = today - birth_data
print('Your age is: {} year and {} days'. format(
time_diff.days // 365, time_diff.days % 365))
except ValueError, KeyError:
# Do your error management here
print('Please use the format YYYY/MM/DD')
print_age()
With this, it should be relatively simple to return True or False and put the function in a loop.
Edit
Here is a piece of code that asks the user for his year of birth and prints the difference:
import datetime
year = None
while year is None:
try:
user_input = raw_input('Enter your date of birth (YYYY): ')
year = int(user_input)
except ValueError:
print('Your did not enter a valid year!')
print('You were born {} years ago'.format(datetime.datetime.now().year - year))
It does not check for the validity of the year though, if you enter 61241, it will not return an error.
You can add a layer of verification that check the range of the year if you wish.
I'm trying to make a basic program that shows how many days are left until your next birthday, however when I run it in terminal, it says that the input value should be returning a string not an integer? when using the input function in python, doesnt it automatically return as a string value?
import datetime
currentDate = datetime.date.today()
userinput = input("Please enter your birthday(MM.DD.YY)")
birthday = datetime.datetime.strptime(userinput, "%m/%d/%Y")
print(birthday)
Use %y (small letter) to catch two digit years
You should advice the user about the expected format - you expect "MM/DD/YY", but you tell the user to type "MM.DD.YY"
To calculate the difference use something like this (for python3, for python2 use raw_input as Jahangir mentioned):
import datetime
today = datetime.date.today()
userinput = input("Please enter your birthday(MM/DD):")
birthday = datetime.datetime.strptime(userinput, "%m/%d")
birthday = datetime.date(year=today.year, month=birthday.month, day=birthday.day)
if (birthday-today).days<0:
birthday = datetime.date(year=today.year+1, month=birthday.month, day=birthday.day)
print("%d days to your next birthday!"%(birthday-today).days)
In Python 2 use raw_input() instead.