Domanda

This program is intended to ask for the date as dd/mm/yyyy. It should then check to see if the user inputted the date in the correct format (dd/mm/yyyy). My program is not able to recognize the format correctly. This is my program:

date = (input("enter the date as dd/mm/yyyy: "))
date = day, month, year = date.split("/")
if date == (day + '/' + month + '/' + year):
    print (date)
    if len(day) == 1 or len(day) == 2:
        print("1")
    if len(month) == 1 or len(month) == 2:
        print("2")
    if len(year) == 4:
        print ("3")
else:
    if len(day) == 1 or len(day) == 2:
        print("4")
    if len(month) == 1 or len(month) == 2:
        print("5")
    if len(year) == 4:
        print ("6")        

The numbers being printed currently have no other purpose than to just check the validity of the date. So far, only 4,5, and 6 are being printed, meaning my program is not recognizing the formatting of the date.

È stato utile?

Soluzione 2

You can use the datetime module:

import datetime

def checkdate(date):

    try:
        datelist = date.split('/')
        datetime.datetime(year=int(datelist[2]), month=int(datelist[1]),day=int(datelist[0]))
        return True
    except:
        return False

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top