Return :class:`datetime.datetime` object from given string,
    or ``None`` if failed to translate.
499448
def string2time(text):
    """"""
    length = len(TIME_FORMAT)
    result = None
    while length:
        try:
            result = datetime.strptime(text, TIME_FORMAT[:length])
        except:
            length -= 1
        else:
            break
    return result
378998
def parse_datetime(dt_str, format):
    """"""
    t = time.strptime(dt_str, format)
    return datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], pytz.UTC)
721177
def parse_datetime(__string: str) -> datetime.datetime:
    
    if not __string:
        datetime_ = datetime.datetime.now(datetime.timezone.utc)
    else:
        # pylint: disable=no-member
        datetime_ = ciso8601.parse_datetime(__string)
    if datetime_.tzinfo is None:
        datetime_ = datetime_.replace(tzinfo=datetime.timezone.utc)
    return datetime_
1280076
def proto_ts_from_datetime_str(dt):
    

    ts = Timestamp()
    if (dt is not None):
        try:
            ts.FromJsonString(dt)
        except ParseError:
            pass
    return ts
432121
def from_str(self, instr):
        ''''''
        if not instr:
            return FlexiDate()

        out = self.our_re.match(instr)
        if out is None:  # no match TODO: raise Exception?
            return None
        else:
            return FlexiDate(
                out.group('year'),
                out.group('month'),
                out.group('day'),
                out.group('hour'),
                out.group('minute'),
                out.group('second'),
                out.group('microsecond'),
                qualifier=out.group('qualifier')
            )
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
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
299229
def from_json(self, value):
        
        if value is None:
            return None

        if isinstance(value, six.binary_type):
            value = value.decode('utf-8')

        if isinstance(value, six.text_type):
            # Parser interprets empty string as now by default
            if value == "":
                return None
            try:
                value = dateutil.parser.parse(value)
            except (TypeError, ValueError):
                raise ValueError("Could not parse {} as a date".format(value))

        if not isinstance(value, datetime.datetime):
            raise TypeError(
                "Value should be loaded from a string, a datetime object or None, not {}".format(type(value))
            )

        if value.tzinfo is not None:  # pylint: disable=maybe-no-member
            return value.astimezone(pytz.utc)  # pylint: disable=maybe-no-member
        else:
            return value.replace(tzinfo=pytz.utc)
685170
def TAF_datetime_to_datetime_object(
    datetime_string             = None,
    datetime_for_year_and_month = None  # e.g. datetime.datetime.utcnow()
    ):

    

    if datetime_string.endswith("24"):

        datetime_string = datetime_string[:-2] + "00"

        tmp = datetime.datetime.strptime(datetime_string, "%d%H") +\
              datetime.timedelta(days = 1)

    else:

        tmp = datetime.datetime.strptime(datetime_string, "%d%H")

    return datetime.datetime(
        datetime_for_year_and_month.year,
        datetime_for_year_and_month.month,
        tmp.day,
        tmp.hour,
        tmp.minute
    )
455554
def _parse_date(cls, date_str: str) -> Optional[datetime.datetime]:
        """"""
        if not date_str:
            return None

        found_time = False
        found_day = False
        found_month = False
        found_year = False

        hour = minute = second = 0
        day = 0
        month = 0
        year = 0

        for token_match in cls.DATE_TOKENS_RE.finditer(date_str):

            token = token_match.group("token")

            if not found_time:
                time_match = cls.DATE_HMS_TIME_RE.match(token)
                if time_match:
                    found_time = True
                    hour, minute, second = [
                        int(s) for s in time_match.groups()]
                    continue

            if not found_day:
                day_match = cls.DATE_DAY_OF_MONTH_RE.match(token)
                if day_match:
                    found_day = True
                    day = int(day_match.group())
                    continue

            if not found_month:
                month_match = cls.DATE_MONTH_RE.match(token)
                if month_match:
                    found_month = True
                    month = month_match.lastindex
                    continue

            if not found_year:
                year_match = cls.DATE_YEAR_RE.match(token)
                if year_match:
                    found_year = True
                    year = int(year_match.group())

        if 70 <= year <= 99:
            year += 1900
        elif 0 <= year <= 69:
            year += 2000

        if False in (found_day, found_month, found_year, found_time):
            return None

        if not 1 <= day <= 31:
            return None

        if year < 1601 or hour > 23 or minute > 59 or second > 59:
            return None

        return datetime.datetime(year, month, day,
                                 hour, minute, second,
                                 tzinfo=datetime.timezone.utc)
930820
def parse_datetime(value):
    """"""

    if isinstance(value, (string_types, text_type, binary_type)):
        value = dateutil.parser.parse(value)
        value.replace(tzinfo=dateutil.tz.tzutc())
        return value
    elif isinstance(value, datetime.datetime):
        value.replace(tzinfo=dateutil.tz.tzutc())
        return value
    elif isinstance(value, datetime.date):
        value = datetime.datetime(value.year, value.month, value.day)
        value.replace(tzinfo=dateutil.tz.tzutc())
        return value
    else:
        raise ValueError('Value must be parsable to datetime object. Got `{}`'.format(type(value)))
1101116
def parse(input):
    '''
    
    '''
    if isinstance(input, datetime):
        return input
    if isinstance(input, date):
        return date_to_datetime(input)
    if isinstance(input, time):
        return time_to_datetime(input)
    if isinstance(input, (int, float)):
        return timestamp_to_datetime(input)
    if isinstance(input, (str)):
        return string_to_data_time(input)
    return None
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)
309408
def from_date(cls, date):
        
        try:
            date = date.date()
        except AttributeError:
            pass
        return cls(date.year, date.month)
141042
def parsehttpdate(string_):
    
    try:
        t = time.strptime(string_, "%a, %d %b %Y %H:%M:%S %Z")
    except ValueError:
        return None
    return datetime.datetime(*t[:6])
572077
def get_formatted_datetime_string(cls, timestamp: int, fmt="%Y-%m-%d %H:%M:%S"):
        
        return time.strftime(fmt, time.localtime(timestamp))
937071
def to_python(self):
        ''''''

        if self.data is None:
            return None

        # don't parse data that is already native
        if isinstance(self.data, datetime.datetime):
            return self.data
        elif self.use_int:
            return datetime.datetime.utcfromtimestamp(self.data / 1000)
        elif self.format is None:
            # parse as iso8601
            return PySO8601.parse(self.data)
        else:
            return datetime.datetime.strptime(self.data, self.format)