from datetime import datetime


def average_sewer_age(sewerdf, snapshot_date=None):
    """
    caculates the length-weighted average age of the assets in the input dataset.
    Snapshot dates allows the returned age to be at a given point in time.
    """
    if not snapshot_date:
        snapshot_date = datetime.now()

    #subset the dataframe to the snapshot date
    subset_sewers = sewerdf.loc[(sewerdf.Year <= snapshot_date.year)]
    #subset_sewers = sewerdf.loc[(sewerdf.index <= snapshot_date.year)]
    subset_length = subset_sewers['Length'].sum()
    if subset_length > 0:
        subset_ages = snapshot_date.year - subset_sewers.Year
        weighted_avg = (subset_ages * subset_sewers.Length).sum() / subset_length

        return weighted_avg

    else:
        return 0