from datetime import datetime


def temporal_filter(record_date_time, time_or_period, op):
    """
    Helper function to perform temporal filters on feature set

    :param record_date_time: datetime field value of a feature
    :type record_date_time: :class:`datetime.datetime`
    :param time_or_period: the time instant or time span to use as a filter
    :type time_or_period: :class:`datetime.datetime` or a tuple of two
                            datetimes or a tuple of one datetime and one
                            :class:`datetime.timedelta`
    :param op: the comparison operation
    :type op: str

    :return: a comparison expression result
    :rtype: bool
    """

    d = datetime.strptime(record_date_time, "%Y-%m-%dT%H:%M:%SZ")
    result = None

    # perform before and after operations
    if op in ['BEFORE', 'AFTER']:
        query_date_time = datetime.strptime(
            time_or_period.value, "%Y-%m-%dT%H:%M:%SZ")
        if op == 'BEFORE':
            return d <= query_date_time
        elif op == 'AFTER':
            return d >= query_date_time

    # perform during operation
    elif 'DURING' in op:
        low, high = time_or_period
        low = datetime.strptime(low.value, "%Y-%m-%dT%H:%M:%SZ")
        high = datetime.strptime(high.value, "%Y-%m-%dT%H:%M:%SZ")
        result = d >= low and d <= high
        if 'BEFORE' in op:
            result = d <= high
        elif 'AFTER' in op:
            result = d >= low
        return result