Represent date and datetime objects as MATCH strings.
854
def _safe_match_date_and_datetime(graphql_type, expected_python_types, value):
    """"""
    # Python datetime.datetime is a subclass of datetime.date,
    # but in this case, the two are not interchangeable.
    # Rather than using isinstance, we will therefore check for exact type equality.
    value_type = type(value)
    if not any(value_type == x for x in expected_python_types):
        raise GraphQLInvalidArgumentError(u'Expected value to be exactly one of '
                                          u'python types {}, but was {}: '
                                          u'{}'.format(expected_python_types, value_type, value))

    # The serialize() method of GraphQLDate and GraphQLDateTime produces the correct
    # ISO-8601 format that MATCH expects. We then simply represent it as a regular string.
    try:
        serialized_value = graphql_type.serialize(value)
    except ValueError as e:
        raise GraphQLInvalidArgumentError(e)

    return _safe_match_string(serialized_value)
352506
def convert_datetime(value, parameter):
    '''
    
    '''
    value = _check_default(value, parameter, ( '', '-', None ))
    if value is None or isinstance(value, datetime.datetime):
        return value
    for fmt in settings.DATETIME_INPUT_FORMATS:
        try:
            return datetime.datetime.strptime(value, fmt)
        except (ValueError, TypeError):
            continue
    raise ValueError("`{}` does not match a format in settings.DATETIME_INPUT_FORMATS".format(value))
78414
def date(self, date):
        """"""
        self._occurrence_data['date'] = self._utils.format_datetime(
            date, date_format='%Y-%m-%dT%H:%M:%SZ'
        )
432752
def calculate_date_strings(self, mode, numDays):
        """"""

        yesterday = date.today() - timedelta(days=1)
        endday = datetime(yesterday.year, yesterday.month, yesterday.day, 23, 59, 59, 999)
        if mode:
            startday = yesterday - timedelta(days=numDays)
        else:
            # daily mode
            startday = yesterday

        return startday.isoformat(), endday.strftime('%Y-%m-%d %H:%M:%S.%f')
735784
def match_date(date, date_pattern):
    
    # unpack the date and pattern
    year, month, day, day_of_week = date
    year_p, month_p, day_p, day_of_week_p = date_pattern

    # check the year
    if year_p == 255:
        # any year
        pass
    elif year != year_p:
        # specific year
        return False

    # check the month
    if month_p == 255:
        # any month
        pass
    elif month_p == 13:
        # odd months
        if (month % 2) == 0:
            return False
    elif month_p == 14:
        # even months
        if (month % 2) == 1:
            return False
    elif month != month_p:
        # specific month
        return False

    # check the day
    if day_p == 255:
        # any day
        pass
    elif day_p == 32:
        # last day of the month
        last_day = calendar.monthrange(year + 1900, month)[1]
        if day != last_day:
            return False
    elif day_p == 33:
        # odd days of the month
        if (day % 2) == 0:
            return False
    elif day_p == 34:
        # even days of the month
        if (day % 2) == 1:
            return False
    elif day != day_p:
        # specific day
        return False

    # check the day of week
    if day_of_week_p == 255:
        # any day of the week
        pass
    elif day_of_week != day_of_week_p:
        # specific day of the week
        return False

    # all tests pass
    return True
1149233
def _get_date_time_format(dt_string):
    '''
    
    '''
    valid_formats = [
        '%I:%M:%S %p',
        '%I:%M %p',
        '%H:%M:%S',
        '%H:%M',
        '%Y-%m-%d',
        '%m-%d-%y',
        '%m-%d-%Y',
        '%m/%d/%y',
        '%m/%d/%Y',
        '%Y/%m/%d'
    ]
    for dt_format in valid_formats:
        try:
            datetime.strptime(dt_string, dt_format)
            return dt_format
        except ValueError:
            continue
    return False
787898
def _clean_datetime(self, obj):
        """"""
        if isinstance(obj, datetime):
            # if it's not naive, put it on zulu time first:
            if obj.tzinfo is not None:
                obj = obj.astimezone(pytz.utc)
            return obj.isoformat()[:self.MAX_LENGTH]
        if isinstance(obj, date):
            return obj.isoformat()
645088
def to_datetime(value):
    """"""
    if value is None:
        return None

    if isinstance(value, six.integer_types):
        return parser.parse(value)
    return parser.isoparse(value)
983585
def date_from_string(string, format_string=None):
    """"""

    if isinstance(format_string, str):
        return datetime.datetime.strptime(string, format_string).date()

    elif format_string is None:
        format_string = [
            "%Y-%m-%d",
            "%m-%d-%Y",
            "%m/%d/%Y",
            "%d/%m/%Y",
        ]

    for format in format_string:
        try:
            return datetime.datetime.strptime(string, format).date()
        except ValueError:
            continue

    raise ValueError("Could not produce date from string: {}".format(string))
909003
def _get_partial_string_timestamp_match_key(self, key, labels):
        """"""
        if isinstance(labels, MultiIndex):
            if (isinstance(key, str) and labels.levels[0].is_all_dates):
                # Convert key '2016-01-01' to
                # ('2016-01-01'[, slice(None, None, None)]+)
                key = tuple([key] + [slice(None)] * (len(labels.levels) - 1))

            if isinstance(key, tuple):
                # Convert (..., '2016-01-01', ...) in tuple to
                # (..., slice('2016-01-01', '2016-01-01', None), ...)
                new_key = []
                for i, component in enumerate(key):
                    if (isinstance(component, str) and
                            labels.levels[i].is_all_dates):
                        new_key.append(slice(component, component, None))
                    else:
                        new_key.append(component)
                key = tuple(new_key)

        return key
523891
def parse_date(date_str: str, pattern=_RE_DATE) -> dt.date:
    """"""

    groups = re.match(pattern, date_str)

    return dt.date(*_date_to_tuple(groups.groupdict()))
1345500
def strip_datetime(value):
        
        if isinstance(value, basestring):
            try:
                return parse_datetime(value)
            except ValueError:
                return
        elif isinstance(value, integer_types):
            try:
                return datetime.datetime.utcfromtimestamp(value / 1e3)
            except (ValueError, OverflowError, OSError):
                return
220201
def to_datetime(date_key):
        '''
        
        '''
        match = re.search(r'\d{4}-\d{2}(-\d{2})?', date_key)
        formatter = '%Y-%m'
        if len(match.group()) == 10:
            formatter += '-%d'
        return datetime.strptime(
            match.group(), formatter).replace(tzinfo=pytz.UTC)
1114553
def parse_value(cls, itype, value):
        """"""

        parsed = None
        if itype == "date":
            m = RE_DATE.match(value)
            if m:
                year = int(m.group('year'), 10)
                month = int(m.group('month'), 10)
                day = int(m.group('day'), 10)
                if cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day):
                    parsed = (year, month, day)
        elif itype == "month":
            m = RE_MONTH.match(value)
            if m:
                year = int(m.group('year'), 10)
                month = int(m.group('month'), 10)
                if cls.validate_year(year) and cls.validate_month(month):
                    parsed = (year, month)
        elif itype == "week":
            m = RE_WEEK.match(value)
            if m:
                year = int(m.group('year'), 10)
                week = int(m.group('week'), 10)
                if cls.validate_year(year) and cls.validate_week(year, week):
                    parsed = (year, week)
        elif itype == "time":
            m = RE_TIME.match(value)
            if m:
                hour = int(m.group('hour'), 10)
                minutes = int(m.group('minutes'), 10)
                if cls.validate_hour(hour) and cls.validate_minutes(minutes):
                    parsed = (hour, minutes)
        elif itype == "datetime-local":
            m = RE_DATETIME.match(value)
            if m:
                year = int(m.group('year'), 10)
                month = int(m.group('month'), 10)
                day = int(m.group('day'), 10)
                hour = int(m.group('hour'), 10)
                minutes = int(m.group('minutes'), 10)
                if (
                    cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day) and
                    cls.validate_hour(hour) and cls.validate_minutes(minutes)
                ):
                    parsed = (year, month, day, hour, minutes)
        elif itype in ("number", "range"):
            m = RE_NUM.match(value)
            if m:
                parsed = float(m.group('value'))
        return parsed
209548
def _match_minimum_date_time(self, match_key, date_time_value, match=True):
        """"""
        if match:
            gtelt = '$gte'
        else:
            gtelt = '$lt'
        if match_key in self._query_terms:
            self._query_terms[match_key][gtelt] = date_time_value
        else:
            self._query_terms[match_key] = {gtelt: date_time_value}
190267
def _encode_datetime(name, value, dummy0, dummy1):
    """"""
    millis = _datetime_to_millis(value)
    return b"\x09" + name + _PACK_LONG(millis)
917826
def stringToDate(fmt="%Y-%m-%d"):
    """"""
    import time
    import datetime
    def conv_func(s):
        return datetime.date(*time.strptime(s,fmt)[:3])
    return conv_func