How can I validate a date in Python 3.x? - python

I would like to have the user input a date, something like:
date = input('Date (m/dd/yyyy): ')
and then make sure that the input is a valid date. I don't really care that much about the date format.
Thanks for any input.

You can use the time module's strptime() function:
import time
date = input('Date (mm/dd/yyyy): ')
try:
valid_date = time.strptime(date, '%m/%d/%Y')
except ValueError:
print('Invalid date!')
Note that in Python 2.x you'll need to use raw_input instead of input.

def validDate(y, m, d):
Result = True
try:
d = datetime.date(int(y), int(m), int(d))
except ValueError, e:
Result = False
return Result
and in the program use the function defined previously:
if not validDate(year_file, month_file, day_file):
return 0

Max S.,
Thanks for the code. Here is how I implemented it:
while True:
date = input('Date (m/dd/yyyy): ')
try:
date = time.strptime(date, '%m/%d/%Y')
break
except ValueError:
print('Invalid date!')
continue

Related

How to check if a datetime is in %d/%m/%Y AND if its greater than a certain datetime

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

How would I limit the user input() to only entering data once per day? I was thinking maybe the datetime stamp but unsure how to implement this

here is my code for retrieving the user input:
def inputQ1():
while True:
try:
Q1A = int(input("Rate your exercise today on scale 1-100: "))
except ValueError:
print("invalid value")
continue
else:
return Q1A
and my code for recording the input into a list:
ansQ1 = []
ansQ1.append(inputQ1())
print(ansQ1)
how do I now ask for this user input again, just once per day?
You can use datetime.datetime.now():
from datetime import datetime
def inputQ1():
while True:
try:
Q1A = int(input("Rate your exercise today on scale 1-100: "))
except ValueError:
print("invalid value")
continue
else:
return Q1A
dates = []
ansQ1 = []
while True:
today = datetime.now().strftime("%Y-%m-%d")
if today not in dates:
ansQ1.append(inputQ1())
dates.append(today)
print(ansQ1)
Where datetime.now().strftime("%Y-%m-%d") returns the current date in the from of 2020-05-21.
One thing to note, it isn't a very good practice to rely on try - except to convert an input into an int. Instead, use the str.isdigit() method:
def inputQ1():
while True:
Q1A = input("Rate your exercise today on scale 1-100: ")
if Q1A.isdigit():
return int(Q1A)
print("invalid value")

i made a function what is meant to check if the format of the date of birth the user enters is correct but i can't get it to work

def checkdob():
while True:
dob = input("Date of Birth")
try:
dob == datetime.datetime.strptime(dob, '%d-%m-%y')
break
except:
print("Incorrect data format, should be DD-MM-YYYY")
checkdob()
I did the following and it works fine. I wonder what you enter as a DOB as an input. Otherwise, it seems to be working fine.
>>> from datetime import datetime
>>> dob = '31-12-99'
>>> if dob:
... dt_obj = datetime.strptime(dob, '%d-%m-%y')
...
>>> print dt_obj
1999-12-31 00:00:00
You can try like this:
def checkdob(dob):
try:
return datetime.datetime.strptime(dob, '%d-%m-%Y')
except ValueError:
print("Incorrect data format, should be DD-MM-YYYY")
return None
while not checkdob(input("Date of Birth")):
pass

Datetime module - ValueError try/except won't work python 3

I have a programming homework assignment. Everything went smoothly until I reached a problem using Try/Except. If I type a valid datetime, the program will take it and it will move on, but if I use a valid datetime format, the exception won't react.
Here is my code:
import datetime
import csv
def get_stock_name(prompt,mode):
while True:
try:
return open(input(prompt) + ".csv")
except FileNotFoundError:
print("File not found. Please try again.")
except IOError:
print("There was an IOError opening the file. Please try again.")
def get_stock_date(prompt):
while True:
try:
return (input(prompt))
except TypeError:
print("Try again.")
except ValueError:
print("Try again.")
def get_stock_purchased(prompt):
while True:
try:
return (input(prompt))
except ValueError:
print("Try again.")
except TypeError:
print("try again.")
stock_name = get_stock_name("Enter the name of the file ==> ", "w")
stock_date = datetime.datetime.strptime(get_stock_date("Enter the stock purchase date ==> " , "%m/%d/%Y"))
stock_sold = datetime.datetime.strptime(get_stock_date("Enter the date you sold the stock ==>" , "%m/%d/%Y"))
stock_purchased = get_stock_purchased("How many stocks were purchased on start date ==>")
To clarify Tigerhawk's initial comment: in order for the try-catch to handle TypeError or ValueError, you need to cast the input to datetime in the try statement.
import datetime
def get_stock_date(prompt):
while True:
try:
return datetime.datetime.strptime(input(prompt), "%m/%d/%Y")
except (ValueError, TypeError):
print("Try again.")
stock_date = get_stock_date("Enter the stock purchase date ==> ")
Additionally, your initial post had strange indentation that made it look like you were making a recursive call to get_stock_date, which caused confusion.
Lastly, you will need to use raw_input if you're using Python 2.
You currently have a loop that will immediately end the function and return a string in any situation I can think of off the top of my head, exceptions that (as just mentioned) I don't think will happen, a call to strptime with the wrong number of arguments, and a recursive call to your function with the wrong number of arguments. And you never save or return a meaningful value. Maybe the recursive call just has wrong indentation? Anyway, you'll have to completely restructure your code, as most of it makes little sense:
import datetime
def get_stock_date(prompt):
while True:
d = input(prompt)
try:
d = datetime.datetime.strptime(d, "%m/%d/%Y")
except (ValueError, TypeError):
print("Try again.")
else:
return d
stock_date = get_stock_date("Enter the stock purchase date ==> ")
I think this is what you are looking for:
def get_stock_date(prompt):
try:
stock_date = datetime.datetime.strptime(prompt, "%m/%d/%Y")
return(stock_date)
except:
print("Try Again.")
prompt = input("Enter the stock purchase date ==> ")
get_stock_date(prompt)
get_stock_date(input("Enter the stock purchase date ==> " ))

python - datetime output time only

The function below takes in HH:MM:SS but returns the date. I just want to enter the time and get out the time.
desired:
enter 23:23:23 > returns 23:23:23
currently:
enter 23:23:23 > returns 1900-01-01 23:23:23
question:
How do i get it to return only 23:23:23 time.
import datetime
def ObtainTime():
while True: #Infinite loop
userInDate = raw_input("Type Time HH:MM:SS ")
try:
d = datetime.datetime.strptime(userInDate, "%H:%M:%S")
break #this will stop the loop
except ValueError:
print "Invalid Input. Please try again.\n"
return d
print ObtainTime()
Completed Code:
import datetime
def ObtainTime():
while True: #Infinite loop
userInDate = raw_input("Type Time HH:MM:SS ")
try:
d = datetime.datetime.strptime(userInDate, "%H:%M:%S")
d = d.time()
break #this will stop the loop
except ValueError:
print "Invalid Input. Please try again.\n"
return d
print ObtainTime()
Use datetime.time() to get the time.
Example -
>>> d = datetime.datetime.strptime("23:23:23","%H:%M:%S")
>>> d.time()
datetime.time(23, 23, 23)

Categories