parse a partial datetime object to a complete datetime object
967262
def _parse(partial_dt):
    
    dt = None
    try:
        if isinstance(partial_dt, datetime):
            dt = partial_dt
        if isinstance(partial_dt, date):
            dt = _combine_date_time(partial_dt, time(0, 0, 0))
        if isinstance(partial_dt, time):
            dt = _combine_date_time(date.today(), partial_dt)
        if isinstance(partial_dt, (int, float)):
            dt = datetime.fromtimestamp(partial_dt)
        if isinstance(partial_dt, (str, bytes)):
            dt = parser.parse(partial_dt, default=timezone.now())

        if dt is not None and timezone.is_naive(dt):
            dt = timezone.make_aware(dt)
        return dt
    except ValueError:
        return None
1134724
def _parse_canonical_datetime(doc, json_options):
    """"""
    dtm = doc["$date"]
    if len(doc) != 1:
        raise TypeError('Bad $date, extra field(s): %s' % (doc,))
    # mongoexport 2.6 and newer
    if isinstance(dtm, string_type):
        # Parse offset
        if dtm[-1] == 'Z':
            dt = dtm[:-1]
            offset = 'Z'
        elif dtm[-3] == ':':
            # (+|-)HH:MM
            dt = dtm[:-6]
            offset = dtm[-6:]
        elif dtm[-5] in ('+', '-'):
            # (+|-)HHMM
            dt = dtm[:-5]
            offset = dtm[-5:]
        elif dtm[-3] in ('+', '-'):
            # (+|-)HH
            dt = dtm[:-3]
            offset = dtm[-3:]
        else:
            dt = dtm
            offset = ''

        # Parse the optional factional seconds portion.
        dot_index = dt.rfind('.')
        microsecond = 0
        if dot_index != -1:
            microsecond = int(float(dt[dot_index:]) * 1000000)
            dt = dt[:dot_index]

        aware = datetime.datetime.strptime(
            dt, "%Y-%m-%dT%H:%M:%S").replace(microsecond=microsecond,
                                             tzinfo=utc)

        if offset and offset != 'Z':
            if len(offset) == 6:
                hours, minutes = offset[1:].split(':')
                secs = (int(hours) * 3600 + int(minutes) * 60)
            elif len(offset) == 5:
                secs = (int(offset[1:3]) * 3600 + int(offset[3:]) * 60)
            elif len(offset) == 3:
                secs = int(offset[1:3]) * 3600
            if offset[0] == "-":
                secs *= -1
            aware = aware - datetime.timedelta(seconds=secs)

        if json_options.tz_aware:
            if json_options.tzinfo:
                aware = aware.astimezone(json_options.tzinfo)
            return aware
        else:
            return aware.replace(tzinfo=None)
    return bson._millis_to_datetime(int(dtm), json_options)
987242
def date_parser(items):
    
    try:
        dt = datetime.strptime(items,"%d/%m/%Y %H:%M:%S")
    except Exception as e:
        try:
            dt = datetime.strptime(items,"%m/%d/%Y %H:%M:%S")
        except Exception as ee:
            raise Exception("error parsing datetime string" +\
                            " {0}: \n{1}\n{2}".format(str(items),str(e),str(ee)))
    return dt
258537
def parse(cls, datestr):
        
        m = DATE_RE.match(datestr)
        if m is not None:
            day = None if m.group(2) is None else int(m.group(2))
            return cls(m.group(4), m.group(3), day, m.group(1))
515191
def parse_date(dateString):
    ''''''
    if not dateString:
        return None
    for handler in _date_handlers:
        try:
            date9tuple = handler(dateString)
        except (KeyError, OverflowError, ValueError):
            continue
        if not date9tuple:
            continue
        if len(date9tuple) != 9:
            continue
        return date9tuple
    return None
898204
def _deserialize_datetime(self, data):
        
        for key in data:
            if isinstance(data[key], dict):
                if data[key].get('type') == 'datetime':
                    data[key] = \
                        datetime.datetime.fromtimestamp(data[key]['value'])
        return data
433877
def parse_datetime(v, default=None, tz=None, exceptions: bool=True) -> datetime:
    
    try:
        t = dateutil_parse(v, default=datetime(2000, 1, 1))
        if tz is None:
            tz = pytz.utc
        return t if t.tzinfo else tz.localize(t)
    except Exception:
        if exceptions:
            raise ValidationError('Failed to parse datetime from "{}"'.format(v))
        return default
649792
def date_to_datetime(d):
    
    if not isinstance(d, datetime):
        d = datetime.combine(d, datetime.min.time())
    return d
309668
def parse(
        self,
        time,  # type: str
        fmt,  # type: str
        now,  # type: pendulum.DateTime
        locale=None,  # type:  typing.Union[str, None]
    ):  # type: (...) -> dict
        
        escaped_fmt = re.escape(fmt)

        tokens = self._FROM_FORMAT_RE.findall(escaped_fmt)
        if not tokens:
            return time

        if not locale:
            locale = pendulum.get_locale()

        locale = Locale.load(locale)

        parsed = {
            "year": None,
            "month": None,
            "day": None,
            "hour": None,
            "minute": None,
            "second": None,
            "microsecond": None,
            "tz": None,
            "quarter": None,
            "day_of_week": None,
            "day_of_year": None,
            "meridiem": None,
            "timestamp": None,
        }

        pattern = self._FROM_FORMAT_RE.sub(
            lambda m: self._replace_tokens(m.group(0), locale), escaped_fmt
        )

        if not re.match(pattern, time):
            raise ValueError("String does not match format {}".format(fmt))

        re.sub(pattern, lambda m: self._get_parsed_values(m, parsed, locale, now), time)

        return self._check_parsed(parsed, now)
553026
def _serialize_datetime(value):
    """"""
    if not isinstance(value, (datetime, arrow.Arrow)):
        raise ValueError(u'The received object was not a datetime: '
                         u'{} {}'.format(type(value), value))
    return value.isoformat()
163629
def to_datetime(plain_date, hours=0, minutes=0, seconds=0, ms=0):
    """"""
    # don't mess with datetimes
    if isinstance(plain_date, datetime.datetime):
        return plain_date
    return datetime.datetime(
        plain_date.year,
        plain_date.month,
        plain_date.day,
        hours,
        minutes,
        seconds,
        ms,
    )
169637
def _parse(self, date_str, format='%Y-%m-%d'):
        
        rv = pd.to_datetime(date_str, format=format)
        if hasattr(rv, 'to_pydatetime'):
            rv = rv.to_pydatetime()
        return rv
102178
def parse_datetime(dt):
    ''''''
    d = datetime.strptime(dt[:-1], ISOFORMAT)

    if dt[-1:] == 'Z':
        return timezone('utc').localize(d)
    else:
        return d
751963
def parse(self, s):
        
        return datetime.datetime.strptime(s, self.date_format).date()
904760
def parse_timestamp(x):
    """"""
    dt = dateutil.parser.parse(x)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=pytz.utc)
    return dt
371224
def _parse_datetime_string(val):
    
    dt = None
    lenval = len(val)
    fmt = {19: "%Y-%m-%d %H:%M:%S", 10: "%Y-%m-%d"}.get(lenval)
    if fmt is None:
        # Invalid date
        raise exc.InvalidDateTimeString("The supplied value '%s' does not "
              "match either of the formats 'YYYY-MM-DD HH:MM:SS' or "
              "'YYYY-MM-DD'." % val)
    return datetime.datetime.strptime(val, fmt)
10028
def _encode_datetime(obj):
    """"""

    if isinstance(obj, datetime.datetime):
        obj = {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f").encode()}
    return obj