Your solution doesn't work because date=day, month, year = date.split("/")
sets date
to a list
, then you're comparing it to a string
(day + '/' + month + '/' + year
). However, your solution is a solved problem, do instead:
import datetime
date = (input("enter the date as dd/mm/yyyy: "))
try: datetime.datetime.strptime(date,"%d/%m/%Y")
except ValueError: # incorrect format
In addition, you probably are turning this into a datetime
object later on anyway, so you can do so in the try
block!
As a further optimization, be aware that many users won't WANT to enter their dates using /
as a datesep! Do some introspection on your input, and adjust your datesep appropriately.
date = input("enter the date: ")
if "-" in date: datesep = "-"
elif "/" in date: datesep = "/"
elif "." in date: datesep = "."
else: datesep = ""
if len(date) < 6: yeartype = "%y"
elif date[-4:-2] not in ("19","20"): yeartype = "%y"
else: yeartype = "%Y"
try: date = datetime.datetime.strptime(date,"%d{0}%m{0}{1}".format(datesep,yeartype))
except ValueError: # invalid date
Now your code will end up with a valid datetime
object of Feb 2nd 2014 for:
- 02022014
- 222014
- 0222014
- 222014
- 020214
- 02214
- 2214
- 02-02-2014
- 02/02/2014
- 2-2-14
- 2/2/2014
- 2/2/14
- etc etc etc