How to specify input as datetime? - python

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))

Related

How to take date as input from user?

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')

Python Specify Input Format as Date

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

i need help adding the leap year functionality into my python program [closed]

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 :')

Python dateutil date conversion

I'm trying to see if a list of dates are valid dates. I'm using the dateutil library, but I'm getting weird results. For example, when I try the following:
import dateutil.parser as parser
x = '10/84'
date = (parser.parse(x))
print(date.isoformat())
I get the result 1984-10-12T00:00:00 which is wrong. Does anyone know why this 12 gets added to the date?
The parse() method parses the string and updates a default datetime object, using the parsed information. If the default is not passed into this function, it uses first second of today.
This means that the 12 in your result, is today (when you're running the code), only the year and the month are updated from parsing the string.
If you need to parse the date string but you're not sure if it's a valid date value, then you may use a try ... except block to catch parse errors.
import dateutil.parser as parser
x = '10/84'
try:
date = (parser.parse(x))
print(date.isoformat())
except ValueError as err:
pass # handle the error
12 is the current date . dateutil takes components from current date/time to account for missing date or year in the date (it does not do this for the month, only date or year). Like another example would be a date like - Janauary 20 - this would get parsed as 2015/01/12 taking the 2015 year from the current datetime.
Sadly I have not yet found any options or such to stop this behavior.
I believe the best option for you would be to come up with a list of the valid datetime formats that you are expecting , and then manually try datetime.datetime.strptime on them , excepting ValueError . Example -
def isdate(dt, fmt):
try:
datetime.datetime.strptime(dt, fmt)
return True
except ValueError:
return False
validformats = [...]
dates =[...]
for x in dates:
if any(isdate(x,fmt) for fmt in validformats):
print(x, 'is valid date')

Difficulty with the replace method

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.

Categories

Resources