MM/DD/YYYY Date to variable conversion m,d, and y - python

I am struggling to find the best way to convert the date input given by the user as mm/dd/yyyy to 3 variables. I am unable to split this because I receive an error since it is a 'float'.
>>> date=3/2/2016
>>> date.split('/')
Traceback (most recent call last):
File "<pyshell#152>", line 1, in <module> date.split('/')
AttributeError: 'float' object has no attribute 'split'
what do I need to add to this to make sure it doesn't evaluate the date with division?
def main():
date=input("Enter date mm/dd/yyyy: ")
I want the input date given as mm/dd/yyyy, and then a way to convert this to 3 variables as m=month d=day y=year
What's the best way to do this?

Try str.split:
>>> test_date = "05/12/2016"
>>> month, day, year = test_date.split('/')
>>> print(f"Month = {month}, Day = {day}, Year = {year}")
Month = 05, Day = 12, Year = 2016

I wrote this following piece of code and it works perfectly fine.
>>> date='3/2/2016'
>>> new=date.split('/')
>>> new
['3', '2', '2016']
>>>
>>> m,d,year=new
>>> m
'3'
>>> d
'2'
>>> year
'2016'
>>>
Like Jessica Smith has already pointed it out, date=3/2/2016 evaluates expressions and divides the numbers. It has to be of string string type to be split.

The error "'float' object has no attribute 'split'" suggests that type(date) == float in your example that implies that you are trying to run Python 3 code using Python 2 interpreter where input() evaluates its input as a Python expression instead of returning it as a string.
To get the date as a string on Python 2, use raw_input() instead of input():
date_string = raw_input("Enter date mm/dd/yyyy: ")
To make it work on both Python 2 and 3, add at the top of your script:
try: # make input() and raw_input() to be synonyms
input = raw_input
except NameError: # Python 3
raw_input = input
If you need the old Python 2 input() behavior; you could call eval() explicitly.
To validate the input date, you could use datetime.strptime() and catch ValueError:
from datetime import datetime
try:
d = datetime.strptime(date_string, '%m/%d/%Y')
except ValueError:
print('wrong date string: {!r}'.format(date_string))
.strptime() guarantees that the input date is valid otherwise ValueError is raised. On success, d.year, d.month, d.day work as expected.
Putting it all together (not tested):
#!/usr/bin/env python
from datetime import datetime
try: # make input() and raw_input() to be synonyms
input = raw_input
except NameError: # Python 3
raw_input = input
while True: # until a valid date is given
date_string = raw_input("Enter date mm/dd/yyyy: ")
try:
d = datetime.strptime(date_string, '%m/%d/%Y')
except ValueError: # invalid date
print('wrong date string: {!r}'.format(date_string))
else: # valid date
break
# use the datetime object here
print("Year: {date.year}, Month: {date.month}, Day: {date.day}".format(date=d))
See Asking the user for input until they give a valid response.
You could use .split('/') instead of .strptime() if you must:
month, day, year = map(int, date_string.split('/'))
It doesn't validate whether the values form a valid date in the Gregorian calendar.

Try:
def main():
month, day, year = [int(x) for x in raw_input("Enter date mm/dd/yyyy: ").split('/')]
print "Month: {}\n".format(month), "Day: {}\n".format(day), "Year: {}".format(year)
main()
Output:
Enter date mm/dd/yyyy: 03/09/1987
Month: 3
Day: 9
Year: 1987

Related

How to limit the input in Python for only dates?

Im currently working on my project.
I want the user to only be allowed to input a date (ex, January 2). If he enters anything else than a date a message should appear like "This is not a date, try again" repeatedly until a real date is given. How do i do this?
My initial idea was to create a .txt file were i write all the 365 dates and then somehow code that the user is only allowed to enter a string that matches one of the elements in the file, else try again.
I would really apreciate your help
Use dateutil.parser to handle dates of arbitrary formats.
Code
import dateutil.parser
def valid_date(date_string):
try:
date = dateutil.parser.parse(date_string)
return True
except ValueError:
return False
Test
for date in ['Somestring', 'Feb 20, 2021', 'Feb 20', 'Feb 30, 2021', 'January 25, 2011', '1/15/2020']:
print(f'Valid date {date}: {valid_date(date)}')
Output
Valid date Somestring: False # detects non-date strings
Valid date Feb 20, 2021: True
Valid date Feb 20: True
Valid date Feb 30, 2021: False # Recognizes Feb 30 as invalid
Valid date January 25, 2011: True
Valid date 1/15/2020: True # Handles different formats
There is no need to store all possible valid dates in a file.
Use datetime.strptime() to parse a string (entered by the user) into a datetime object according to a specific format.
strptime will raise an exception the input specified does not adhere to the pattern, so you can catch that exception and tell the user to try again.
Wrap it all in a while loop to make it work forever, until the user gets it right.
You can start with this:
from datetime import datetime
pattern = '%B %d, %Y' # e.g. January 2, 2021
inp = ''
date = None
while date is None:
inp = input('Please enter a date: ')
try:
date = datetime.strptime(inp, pattern)
break
except ValueError:
print(f'"{inp}" is not a valid date.')
continue
For a full list of the %-codes that strptime supports, check out the Python docs.
Provide you with several ways to verify the date, these are just simple implementations, and there is no strict check, you can choose one of the methods and then supplement the detailed check by yourself.
Use date(year,month,day)
def isValidDate(year, month, day):
try:
date(year, month, day)
except:
return False
else:
return True
Use date.fromisoformat()
def isValidDate(datestr):
try:
date.fromisoformat(datestr)
except:
return False
else:
return True
Use strptime
def check_date(i):
valids = ['%Y-%m-%d', '%Y%M']
for valid in valids
try:
return strptime(i, valid)
except ValueError as e:
pass
return False
Use regex
def check_date(str):
reg = /^(\d{4})-(\d{2})-(\d{2})$/;
return reg.test(str)

Python Dateutil Parsing: Minimum number of components

The python dateutils package allows to parse date(time)s without specifying a format. It attempts to always return a date, even when the input does not appear to be one (e.g. 12). What would be a pythonic way to ensure at least a day, month and year component to be present in the input?
from dateutil import parser
dstr = '12'
dtime = parser.parse(dstr)
Returns
2019-06-12 00:00:00
One way you could do it is by splitting the input string on the likely date delimiters (e.g., ., -, :). So, this way you could input 2016.5.19 or 2016-5-19.
from dateutil import parser
import re
def date_parser(thestring):
pieces = re.split('\.|-|:', thestring)
if len(pieces) < 3:
raise Exception('Must have at least year, month and date passed')
return parser.parse(thestring)
print('---')
thedate = date_parser('2019-6-12')
print(thedate)
print('---')
thedate = date_parser('12')
print(thedate)
This will output:
---
2019-06-12 00:00:00
---
Traceback (most recent call last):
File "bob.py", line 18, in <module>
thedate = date_parser('12')
File "bob.py", line 9, in date_parser
raise Exception('Must have at least year, month and date passed')
Exception: Must have at least year, month and date passed
So the first one passes are there are 3 "pieces" to the date. The second one doesn't.
This will get dodgy depending on what is in the re.split, one will have to make sure all the right delimiters are in there.
You could remove the : in the delimiters if you want just typical date delimiters.

Need a password to be equal to the date (d/m/y)

our teacher gave us this assignment to make a "password" (not a login, basically make a variable that is always equal to the date and then "if- else" it so the variable is equal to the date )
the code u see is all I tried, I couldn't find anything on the web.
import datetime
x = datetime.datetime.now()
xd=x.strftime("%d")
xm=x.strftime("%m")
xy=x.strftime("%Y")
Date = [xd,xm,xy]
password=input("what is the password?")
if password==Date:
print("well done")
else:
print("try again")
I have no syntax errors
You're going at it in too "divided" of an approach. You can translate the date into a string all at once:
import datetime
x = datetime.datetime.now()
date = x.strftime("%d%m%Y") # will produce '05212019'
# alternatively: "%d,%m,%Y" would produce '05,21,2019' - you can customize this format
password = input("Enter the password. ")
if password == date:
print("Well done")
else:
print("Try again")
First Date is a reserved word so I recommend using date.
date is a list and password is a string so you need to change Date to string
date = ''.join(date) # 21052019
OR
change password to list (assuming input like 21 05 2019)
password = input("what is the password?").split(' ') # ['21', '05', '2019']
OR
don't create a list and just generate the password/date with datetime
date = x.strftime("%d%m%Y") # 21052016
Not sure which format you're after but you could do something like this and then modify the format so that it looks exactly as you need it:
>>> import datetime
>>> datetime.date.today().strftime("%B %d, %Y")
'May 21, 2019'
You could change to ...
*.strftime("%B%d%Y")
... for example if you needed it to remove spaces and commas.
This site https://www.programiz.com/python-programming/datetime/strftime has a very good format code list (%h, %d, %y, etc...) in case you're needing your time bits in different formats.
Right now, Date is a list and password is a string. You'll need to change one to match the other, or they'll never compare equal.
import datetime
x = datetime.datetime.now()
xd=x.strftime("%d")
xm=x.strftime("%m")
xy=x.strftime("%Y")
Date = xd+","+xm+","+xy
password=input("what is the password?")
if password==Date:
print("well done")
else:
print("try again")

How to convert a downloaded string to datetime format?

I am trying to check if today's date < date downloaded from text file online. Here is my code :
import datetime
import requests
URL = "http://directlinktotextfile.com/text.txt"
result = requests.get(URL)
today = datetime.datetime.now().date()
Url_date = result.text
Url_date.strip()
Url_date = datetime.date(Url_date)
if today < Url_date :
print "Today is less than future date"
raw_input()
else:
print "Today is greater than or = to future date"
raw_input()
The result that comes back is just this : 2018,02,14. I use .strip() in case there might be blank spaces or extra lines. I've printed out result.text after strip() and it shows the correct details. Why is it that I can't check if today < Url_date. It works fine if I enter manually a date into datetime.date(2018,02,14), but when I'm downloading the string it won't work. Any suggestions?
You pass string to datetime.date() which should be each an integer.
Url_list = []
Url_list = Url_date.split(",")
yr = int(Url_list[0])
mn = int(Url_list[1])
d = int(Url_list[2])
Now pass these integers to datetime.date
Url_date = datetime.date(yr, mn, d)
The arguments you pass to datetime.date(arg1, arg2, arg3) are not strings as a whole. When you pass it from url, what you are actually doing is
datetime.date("2018,2,14")
Note that you are passing only one string argument and not 3 different integers. You should split the date string using comma and then convert each into integers and then pass them as arguments to datetime.date.
Here is what your code is trying to do :
Url_date = datetime.date("2018,02,14")
But he wants to have:
Url_date = datetime.date(2018,02,14)
Do
Url_date.split(',') # Result: ['2018','02','14']
And then convert all the string in the array in integers
It should be ok :)
Use strptime:
import datetime
today = datetime.datetime.now().date()
parsed = datetime.datetime.strptime("2018,02,14", "%Y,%m,%d").date()
print(today < parsed) # True

How to make strings within strings optional in python

I am writing to write something where there are two variables that are formatted in datetime format. The way the user may input their date and time may have the letter "Z" at the end of it. For example:
"2008-01-01T00:00:01Z"
The user may or may not enter in the "Z" at the end so I want to do something that makes either format acceptable. Here's what I have:
import datetime
b = datetime.datetime.strptime("2008-01-01T00:00:01Z", "%Y-%m-%dT%H:%M:%S")
c = datetime.datetime.strptime("2008-05-01T23:59:00Z", "%Y-%m-%dT%H:%M:%S")
def startTime(b):
try:
datetime.datetime.strptime(b, "%Y-%m-%dT%H:%M:%S")
except:
print "Error: start time is invalid."
def endTime(c):
try:
datetime.datetime.strptime(c, "%Y-%m-%dT%H:%M:%S")
except:
print "Error: end time is invalid."
How about just manually removing the Z if it is there?
user_in = raw_input("Please enter a date")
if user_in.endswith('Z'): user_in = user_in[:-1]
rstrip can remove the Z for you if it exists, and leave the string alone otherwise:
>>> "2008-05-01T23:59:00Z".rstrip("Z")
'2008-05-01T23:59:00'
>>> "2008-05-01T23:59:00".rstrip("Z")
'2008-05-01T23:59:00'
So if you have a date s in string format,
date = datetime.datetime.strptime(s.rstrip("Z"), "%Y-%m-%dT%H:%M:%S")
will handle both cases.

Categories