日期验证器/格式化器 returns None?

Date validator / formatter returns None?

我需要一个将日期字符串作为输入的函数,然后验证输入的格式是否为 %m/%d%Y (MM/DD/YYYY) 或将给定日期重新格式化为该格式。但是,当我 运行 以下内容时,我打印:“日期是:None”。任何人都可以提供一些指导如何解决这个问题吗?非常感谢任何帮助!

import datetime

test_date = "08/19/2020"

def date_fixer(date_string):
    '''takes a date as input and reformats if needed.'''
    format = "%m/%d/%Y"
    date_string = str(date_string)
    try:
        datetime.datetime.strptime(date_string, format)
        print("This is the correct date string format.")
    except ValueError:
        print("This is the incorrect date string format. It should be %m/%d/%Y")
        #convert
        date_string = parse(str(date_string)).strftime('%m/%d/%Y')
        return(date_string)

date = date_fixer(test_date)
print("date is: " + str(date))

return 位于 except 块内,这就是日期格式有效时 return 在 None 中的原因。

你可以尝试以下方法吗:

import datetime

test_date = "08/19/2020"

def date_fixer(date_string):
    '''takes a date as input and reformats if needed.'''
    format = "%m/%d/%Y"
    date_string = str(date_string)
    try:
        datetime.datetime.strptime(date_string, format)
        print("This is the correct date string format.")
    except ValueError:
        print("This is the incorrect date string format. It should be %m/%d/%Y")
        #convert
        date_string = parse(str(date_string)).strftime('%m/%d/%Y')
    return(date_string)

date = date_fixer(test_date)
print("date is: " + str(date))

您的代码中的错误已由其他人解释,但是,通知用户输入字符串是否为预期格式是否重要很重要吗?如果不是简单地 运行 dateutil.parser.parse() 日期字符串和 return 重新格式化的字符串:

from dateutil.parser import parse

def date_fixer(date_string, format="%m/%d/%Y"):
    '''takes a date as input and reformats in the specified format.'''
    return parse(str(date_string)).strftime(format)

>>> date_fixer("08/19/2020")
'08/19/2020'
>>> date_fixer("19/08/2020")
'08/19/2020'
>>> date_fixer("2020-08-19")
'08/19/2020'
>>> date_fixer("08/19/2020", '%Y-%m-%d')    # override default format
'2020-08-19'