How to take date as input from user? - python

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

Related

Date print in Python

i want to create a function in which the writes a date to his choice in dd/mm/yyyy type, and then it will print the day in the week for the wrriten date (i'm a begginer so should use simple slicing/conditions/imports (i was told as a clue to use calender.weekday).
for ex:
Enter a date: 01/01/2000
Saturday
Enter a date: 27/11/2051
Monday
Use datetime()
from datetime import datetime
day = input("Enter your date in the format dd/mm/yy")
day = datetime.strptime(day, "%d/%m/%y")
print(day.strftime('%A'))`

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

How to specify input as datetime?

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

Need Assistance with This Simple Python Code

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)

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