[Python] Determine whether a given date string includes all three components: day, month, and...

Discussão em 'Python' iniciado por Stack, Fevereiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to determine whether a given date string includes all three components: day, month, and year.

    Example Inputs and Expected Outputs:

    • "2025-01-01" → True (All components are present)
    • "January 31, 2026" → True (Natural language format with all components)
    • "January 2026" → False (Day is missing)
    • "2026" → False (Month and day are missing)
    • "2025-01" -> False

    Approach I Am Using:

    I am currently using the dateutil.parser.parse function to parse the date string and then check whether the year, month, and day attributes in the resulting datetime object are valid. However, the parse function fills in missing components with default values, making it hard to determine whether these components were explicitly provided in the input string. So, I wrote the below logic to get around that problem.

    def parse_date(date_string):
    try:
    default_dt1 = datetime(1,1,1)
    default_dt2 = datetime(2,2,2)
    parsed_date1 = dateutil.parser.parse(date_string,default=default_dt1)
    parsed_date2 = dateutil.parser.parse(date_string,default=default_dt2)
    if parsed_date1 == parsed_date2:
    # print(parsed_date1.month)
    return True
    return False
    except (ValueError,TypeError):
    return False


    How it works:

    Default Dates:
    The function uses two default dates, datetime(1, 1, 1) and datetime(2, 2, 2), to fill in missing components when parsing the input date string.

    Parsing:
    It parses the date_string twice using the parser.parse function (from the dateutil.parser module) with the two different default dates. If the date_string is missing components (like a day or month), parser.parse will use the defaults to fill in the gaps.

    Comparison:
    If both parsed results are the same, it indicates that the date_string has all components, as missing components would lead to differences in the two parsed dates due to the different defaults.

    Question:
    How can I reliably check if a date string explicitly contains all three components without relying on default values added by dateutil? Is there a better way to achieve this?. I tried giving default values as none but it is not working. surprisingly there is no default functionality for achieving this.

    Note: the input format is not consistent.

    Continue reading...

Compartilhe esta Página