简体   繁体   中英

How to check date format if it have different input like 'yyyy-mm-dd' or 'yyyymmdd'?

i have question how to check date input?

Here's some algorithm that i make

#The input
Enter the date: yyyy-mm-dd #The format is string
or
Enter the date: yyyymmdd


if the input like yyyy-mm-dd:
   print(yyyy-mm-dd)
else if the input like yyyymmdd:
   print(yyyy-mm-dd)
else: #If the input have alphabet
   print ("Sorry, wrong format bro!")

Is it possible?

This ensures a valid date format goes through. The regex solution will allow in stuff like 2020-99-99.

import datetime

date = "2020-02-01"

def format_check(date, fmt):
    try: datetime.datetime.strptime(date, fmt)
    except: return False
    else: return True
    
if not format_check(date, '%Y-%m-%d') and not format_check(date, '%Y%m%d'):
    raise ValueError("Sorry, wrong format bro!")

您可以使用像 re'\\d{4}-\\d{2}-\\d{2}' 这样的正则表达式,在这里我们需要正好 4 个数字,2 个数字,然后是另外 2 个代表天和月的数字,然后是 4 个数字代表年份

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM