So I have the following input prompt:
start_date = input("What is the start date in format mm/dd/yyyy: ")
I want to make it so that if someone does not give an input in the proper format they are simply reprompted to do it again. Format is provided above, so something like January 20, 2020 being 01/20/2020, and the preceding 0 for January is important. I guess you'd also have to make sure they don't input impossible values like a 13th month of a 40th day of the month. I assume it would be something like:
while True:
start_date = input("What is the start date in format mm/dd/yyyy: ")
if ##properly formatted
break
The datetime module, through its datetime class, provides a very helpful method called strptime(), that it seems like what you need for your case. You can read more about it here
You could use it as follows:
while True:
try:
start_date = datetime.datetime.strptime(
input("What is the start date in format mm/dd/yyyy: "), "%m/%d/%Y"
)
except ValueError:
print("Invalid date")
else:
break
# You can keep using the start_date variable from now on
Related
I just want to write a script for taking the date
as input from user, if user don't enter date then program should take system's date.
I tried the following code. How can I do this by using any if-else condition or any functions in Python.
date_entry = input('Enter a date in YYYY-MM-DD format:')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
How can I write this script for above problem?
It's best to use exception handling for this matter.
Use try and except to handle any exceptions thrown by datetime module whenever any input given is not according to the format wanted.
try:
date_entry = input('Enter a date in YYYY-MM-DD format:')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
except ValueError:
date1=datetime.date.today().strftime('%Y-%m-%d')
My project involves reading CSV files concering city data and then computing various statistics. I am trying to create a function that will take city data from a CSV and the create a copy of the data except with a date filter applied. The user is prompted to enter a starting and ending date.
I am currently just testing and trying to get the data to print with the correct date filters applied. My biggest problem so far is that I can't seem to convert the strings entered by the user into a datetime format. Is there a way for the user to directly enter the data in datetime format?
def date_filtering(city_file):
date1 = input('Please enter a valid start date that you wish to explore?\n'
date2 = input('Please enter a valid end date.')
print(city_file.loc[date1:date2])
Thanks in advance!
I am working of the assumption you only need date, because you make no mention of time in the code. What you need to do is parse the input somehow to get the year, month, and day. I am sure it could be done using regex, but it is simpler to do it just with python builtins.
A normal way of representing date in the US is mm/dd/yyyy, so I will use that.
def strtodatetime(str):
month, day, year = [int(d) for d in str.split("/")]
return datetime.date(year, month, day)
date1 = strtodatetime(input('Please enter a valid start date that you wish to explore?\n'))
date2 = strtodatetime(input('Please enter a valid end date.'))
The strtodatetime splits the input string by the "/" character, then casts each element in the resultant list to integers. Then it returns a new datetime.date object with the corresponding dates.
If you are worried about the user inputting something of the wrong format, you can use a try block to make sure they don't. There are three possible sources of exceptions I can see, the user can input too many or too few /'s (like 10/2/1999/2), the user can input a date that doesn't exist (like 13/32/-1), or the user can input something that can't be cast to an int (like March/22/1999). All three raise ValueErrors, so that is the only exception we need to catch here. To catch that, we would change our code to
def strtodatetime(str):
month, day, year = [int(d) for d in str.split("/")]
return datetime.date(year, month, day)
date_filtering(city_file):
try:
date1 = strtodatetime(input('Please enter a valid start date that you wish to explore?\n'))
date2 = strtodatetime(input('Please enter a valid end date.'))
except ValueError:
print('Please enter a valid date in the format mm/dd/yyyy')
return date_filtering(city_file)
return city_file.loc[date1:date2]
print(data_filtering(city_file))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
import math
repeat = True
date = raw_input('Enter a date in the format MM/DD/YYYY') #Prompts user to input
while repeat:
date_month = date[0:2] #Takes the input's month and keeps its value for the varible date_month
date_day = date[3:5] #Takes the input's day and keeps its value for the varible date_day
date_year = date[6:10] #Takes the input's year and keeps its value for the varible date_year
if 00 < int(date_month) < 13:
if 00 < int(date_day) < 32:
if 0000 < int(date_year) < 2017:
date = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY')
else:
date = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY')
Roll-your-own parser code is silly. Python has batteries included for this:
import datetime
repeat = True
datestr = raw_input('Enter a date in the format MM/DD/YYYY')
while repeat:
try:
# Parse to datetime, then convert to date since that's all you use
date = datetime.datetime.strptime(datestr, '%m/%d/%Y').date()
except ValueError:
pass # Handle bad dates in common code
else:
if 0 < date.year < 2017:
datestr = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY')
continue # Bypass invalid date input common code
# Both exception and invalid years will fall through to this common code
datestr = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY')
Obviously, as written, this doesn't actually terminate the loop under any conditions, but neither does your original code. The advantage here is that strptime does the heavy lifting; it validates many more things that your original code, through a single try/except, and handles tricky stuff like days of the month by month without special checks. You can access the year, month and day attributes of the date object it parses as before, as Python native ints, no individual int conversions as you go.
Note that if you wanted to use locale appropriate date representations, the format you chose happens to exactly match for en_US locale, and you could make it more portable to non-U.S. users by just using datetime.datetime.strptime(datestr, '%x') (though you'd have to make the raw_input prompt dynamic to match); that works the same as '%m/%d/%Y' for en_US, but switches ordering and separators for, say, a German locale, which would make it equivalent to '%d.%m.%Y'.
It is as simple as this:
>>> import calendar
>>> print(calendar.isleap(1999))
False
>>> print(calendar.isleap(2004))
True
There a more problems with the question than just if the year is leap or not. #Dex'ter solution will indeed tell you if year is leap or not, but thing is you can't really ask for that in the end. So your first question should be is the user input date a leap year:
if calendar.isleap(date_year):
, followed by month for which your code is functional. And than you)ll have another problem in the day.
if 00 < int(date_day) < 32:
This will give you erroneous results no matter if the year is leap or not because there are plenty of months than don't have 31 days. For that I would advise:
>>> from calendar import monthrange
>>> monthrange(2011, 2)
EDIT: and by the way this last function supports leap year as well.
I rewrite your program.I wish it will help
import math
from datetime import datetime
repeat = True
date = raw_input('Enter a date in the format MM/DD/YYYY :')
while repeat:
try:
datetime.strptime(date, "%m/%d/%Y")
date = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY :')
except ValueError:
date = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY :')
Here is my code & this is my error : AttributeError: type object 'datetime.datetime' has no attribute 'strptime
#Trying to calculate how many days until a project is due for
import datetime
project = input('When is your project due for Please specify mm/dd/yyyy ')
deadline = datetime.datetime.strptime(project, '%m/%d/Y').date()
days = project - deadline
print(days)
print(days.days)
Thank You in advance #KOH
Looks like you need something like this:
import datetime
project = input('When is your project due for. Please specify mm/dd/yyyy ')
deadline = datetime.datetime.strptime(project, '%m/%d/%Y').date()
delta = deadline - datetime.datetime.now().date()
print(delta.days)
Using Python3 there is no errors with datetime:
>>> datetime.datetime.strptime("08/11/2015", "%m/%d/%Y").date()
datetime.date(2015, 8, 11)
I'm not sure why you were getting that AttributeError, but I guess we resolved it in the comments. You were also getting an error because your formatting string was missing a %. And once you fix that, you would get an error saying you can't subtract a date from a str.
Even with all the errors fixed, what the code is doing isn't what you're trying to do. It looks like you're trying to subtract the user-provided date from itself, but I'm guessing you want to subtract today's date from the user-provided date, in order to get the number of days until the user-provided date.
Here's the fixed code, with some formatting and other changes thrown in.
from datetime import datetime
deadline_str = input('When is your project due? Specify mm/dd/yyyy: ')
deadline = datetime.strptime(deadline_str, '%m/%d/%Y').date()
days_till_deadline = (deadline - datetime.today().date()).days
print("{0} days till the project is due.".format(days_till_deadline))
So this is the code written by me and it works...
#todays date programme
import datetime
currentDate = datetime.date.today()
#currentDate is date which is converted to string with variable current in the format dd/mm/yyyy
current = datetime.datetime.strftime(currentDate, '%d/%m/%Y')
#input statements
userInput = input('Please enter your project deadline (dd/mm/yyyy)\n')
print()
##prints...
print("Today's Date is "+current)
print()
print("Your project deadline is " + userInput)
#userInput is a string which is converted to date with variable Input
Input = datetime.datetime.strptime(userInput, "%d/%m/%Y").date()
##Calculating remaining days
remainingDays = Input - currentDate
remainingDays = remainingDays.days
print()
print('The days remaining for deadline are '+str(remainingDays)+' days')
I guess it's something like this.
Because here we had to import the date time first cos we working with the date.
Then we had to get the current date in order to be able to get the project deadline.
import datetime
current_date = datetime.datetime.now()
user = input('Enter the days left for your project: ')
deadline = datetime.datetime.strptime(user, '%d%m%Y').date()
days_left = deadline - current_date.date()
print(days_left.days)
I must have the user enter a date in mm/dd/yy format and then output the string in long-date format like January, ##, ####. I cannot for the life of me get the month to replace as a the word.
def main():
get_date=input('Input a date in mm/dd/yy format!\nIf you would like to enter a 1-digit number, enter a zero first, then the number\nDate:')
month= int(get_date[:2])
day=int(get_date[3:5])
year=int(get_date[6:])
validate(month, day, year)#validates input
get_month(get_date)
def validate(month,day,year):
while month>12 or month<1 or day>31 or day<1 or year!=15:
print("if you would like to enter a one-digit number, enter a zero first, then the number\n theres only 12 months in a year\n only up to 31 days in a month, and\n you must enter 15 as the year")
get_date=input('Input a date in mm/dd/yy format!:')
month= int(get_date[:2])
day=int(get_date[3:5])
year=int(get_date[6:])
def get_month(get_date):
if get_date.startswith('01'):
get_date.replace('01','January')
print(get_date)
I have tried a plethora of things to fix this but I cannot make January appear instead of 01.
Strings in Python are immutable, they don't change once they're created. That means any function that modifies it must return a new string. You need to capture that new value.
get_date = get_date.replace('01','January')
You can do this (and simplify the code) using python's date module.
The strptime function will parse a date from a string using format codes. If it's can't parse it correctly, it will raise a value error, so no need for your custom validation function
https://docs.python.org/2.7/library/datetime.html#datetime.datetime.strptime
The strftime function will print out that date formatted according to the same codes.
https://docs.python.org/2.7/library/datetime.html#datetime.datetime.strftime
Updated, your code would look something like this:
from datetime import datetime
parsed = None
while not parsed:
get_date=input('Input a date in mm/dd/yy format!\nIf you would like to enter a 1-digit number, enter a zero first, then the number\nDate:')
try:
parsed = datetime.strptime(get_date, '%m/%d/%y')
except ValueError:
parsed = None
print parsed.strftime('%B %d, %Y')
Why don't you use datetime module ?
year = 2007; month=11; day=3
import datetime
d = datetime.date(year, month, day)
print d.strftime("%d %B %Y")
You might be better off using Python's datetime module for this:
from datetime import datetime
entered_date = input('Input a date in mm/dd/yy format!\nIf you would like to enter a 1-digit number, enter a zero first, then the number\nDate:')
d = datetime.strptime(entered_date, '%m/%d/%y')
entered_date = d.strftime('%B, %d, %Y')
e.g.
'February, 29, 2016'
This way you catch invalid dates (such as 02/29/15) as well as badly-formatted ones.