【问题标题】:Checking the format/contents of a string检查字符串的格式/内容
【发布时间】:2014-02-14 23:13:30
【问题描述】:

该程序旨在要求日期为 dd/mm/yyyy。然后它应该检查用户是否以正确的格式 (dd/mm/yyyy) 输入了日期。我的程序无法正确识别格式。这是我的程序:

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

目前打印的数字除了检查日期的有效性之外没有其他目的。到目前为止,只打印了 4,5 和 6,这意味着我的程序无法识别日期的格式。

【问题讨论】:

  • 这是 Python3,是吗?这对这段代码至关重要,因此您可能希望对其进行标记。
  • 您将date 重新分配给一个列表,然后期望它等于一个字符串。
  • @Manaar 您可能希望查看我编辑的答案,以便轻松地为您的脚本添加更多功能。

标签: python date python-3.x python-datetime


【解决方案1】:

您的解决方案不起作用,因为date=day, month, year = date.split("/") 将date 设置为list,然后您将其与string (day + '/' + month + '/' + year) 进行比较。但是,您的解决方案是已解决的问题,请改为:

import datetime
date = (input("enter the date as dd/mm/yyyy: "))

try: datetime.datetime.strptime(date,"%d/%m/%Y")
except ValueError: # incorrect format

此外,您可能稍后会将其转换为 datetime 对象,因此您可以在 try 块中这样做!

作为进一步的优化,请注意许多用户不希望使用/ 作为日期间隔来输入他们的日期!对您的输入进行一些内省,并适当调整您的日期间隔。

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

现在您的代码将以 2014 年 2 月 2 日的有效 datetime 对象结束:

  • 02022014
  • 222014
  • 0222014
  • 222014
  • 020214
  • 02214
  • 2214
  • 02-02-2014
  • 2014 年 2 月 2 日
  • 2-2-14
  • 2014 年 2 月 2 日
  • 2/2/14
  • 等等等等等等

【讨论】:

    【解决方案2】:

    您可以使用datetime 模块:

    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
    

    【讨论】:

    • 谢谢。虽然返回函数没有提供输出,所以我改为使用 print() 函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2019-04-22
    • 2013-02-04
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    相关资源
    最近更新 更多