📜  Python - 验证字符串日期格式

📅  最后修改于: 2022-05-13 01:55:43.881000             🧑  作者: Mango

Python - 验证字符串日期格式

给定日期格式和字符串日期,任务是编写一个Python程序来检查日期是否有效并与格式匹配。

例子:

方法 #1:使用 strptime()

在这种情况下,函数strptime 通常用于将字符串日期转换为日期时间对象,当它与格式或日期不匹配时使用,引发 ValueError,因此可用于计算有效性。

Python3
# Python3 code to demonstrate working of
# Validate String date format
# Using strptime()
from datetime import datetime
 
# initializing string
test_str = '04-01-1997'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing format
format = "%d-%m-%Y"
 
# checking if format matches the date
res = True
 
# using try-except to check for truth value
try:
    res = bool(datetime.strptime(test_str, format))
except ValueError:
    res = False
 
# printing result
print("Does date match format? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Validate String date format
# Using dateutil.parser.parse
from dateutil import parser
 
# initializing string
test_str = '04-01-1997'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing format
format = "%d-%m-%Y"
 
# checking if format matches the date
res = True
 
# using try-except to check for truth value
try:
    res = bool(parser.parse(test_str))
except ValueError:
    res = False
 
# printing result
print("Does date match format? : " + str(res))


输出:

The original string is : 04-01-1997
Does date match format? : True

方法 #2:使用 dateutil.parser.parse()

在此,我们使用不同的内置函数dateutil.parser 检查验证格式。这不需要检测日期的格式。

蟒蛇3

# Python3 code to demonstrate working of
# Validate String date format
# Using dateutil.parser.parse
from dateutil import parser
 
# initializing string
test_str = '04-01-1997'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing format
format = "%d-%m-%Y"
 
# checking if format matches the date
res = True
 
# using try-except to check for truth value
try:
    res = bool(parser.parse(test_str))
except ValueError:
    res = False
 
# printing result
print("Does date match format? : " + str(res))

输出:

The original string is : 04-01-1997
Does date match format? : True