Home > Enterprise >  Check if date format contains year or month?
Check if date format contains year or month?

Time:01-15

I can have a date string such as :

4.3.2009 (my output is 'day' because user meant a day)
3.2009 (my output is 'month' because user meant March)
4/3/2009 (same - output is day)
4-2009 ( output is month)

I am using dateutil to parse the string but can't check format. I just need to know the type, doesn't matter if it's 'month', 'M', or other output. I know I can ask the format with datetime.strftime(string,format) but this won't help.

CodePudding user response:

You can do this just by splitting the date strings like this:

dates = ['4.3.2009', '3.2009', '4/3/2009', '4-2009']

def check(date):
    for c in date:
        if not c.isdigit():
            t = date.split(c)
            if len(t) == 2:
                return 'month'
            if len(t) == 3:
                return 'day'
            break
    return None

for date in dates:
    print(check(date))

Output:

day
month
day
month

Note:

check() function will return None if the input string does not contain something that looks like a date. It does not validate the given string. For example, '99-99-99' would return 'day'. You could extend the function to build a strptime format string based on the identified separator

CodePudding user response:

For diversity matching, you can use regular expressionsre.

(\d{1,2}\D ?)?(\d{1,2}\D ?\d{4})

When the match is successful and there is a value in group 1, it means day, and when the match is successful and group 1 has no value, it means month.

import re

dates_str = ['4.3.2009', '3.2009', '4/3/2009', '4-2009']

regex = re.compile(r"(\d{1,2}\D ?)?(\d{1,2}\D ?\d{4})")


def func(v):
    res = regex.match(v)
    if res:
        if all(res.groups()):
            return "day"
        else:
            return "month"
    return ""


for date_str in dates_str:
    print(func(date_str))

Output:

day
month
day
month
  •  Tags:  
  • Related