Converts openssl ASN1_TIME object to python datetime.datetime
970601
def _X509__asn1date_to_datetime(asn1date):
    
    bio = Membio()
    libcrypto.ASN1_TIME_print(bio.bio, asn1date)
    pydate = datetime.strptime(str(bio), "%b %d %H:%M:%S %Y %Z")
    return pydate.replace(tzinfo=utc)
991736
def str_to_time(time_str: str) -> datetime.datetime:
    
    pieces: Any = [int(piece) for piece in time_str.split('-')]
    return datetime.datetime(*pieces)
107411
def time_range(from_=None, to=None):  # todo datetime conversion
    
    args = locals()
    return {
        k.replace('_', ''): v for k, v in args.items()
    }
573283
def strptime(time_str, time_format):
        
        try:
            datetime_obj = datetime.strptime(time_str, time_format)
            return datetime_obj
        except ValueError as ex:
            raise ValueError(ex)
1117725
def asDateTime(self):
        
        text = str(self)
        if text.endswith('Z'):
            tzinfo = TimeMixIn.UTC
            text = text[:-1]

        elif '-' in text or '+' in text:
            if '+' in text:
                text, plusminus, tz = string.partition(text, '+')
            else:
                text, plusminus, tz = string.partition(text, '-')

            if self._shortTZ and len(tz) == 2:
                tz += '00'

            if len(tz) != 4:
                raise error.PyAsn1Error('malformed time zone offset %s' % tz)

            try:
                minutes = int(tz[:2]) * 60 + int(tz[2:])
                if plusminus == '-':
                    minutes *= -1

            except ValueError:
                raise error.PyAsn1Error('unknown time specification %s' % self)

            tzinfo = TimeMixIn.FixedOffset(minutes, '?')

        else:
            tzinfo = None

        if '.' in text or ',' in text:
            if '.' in text:
                text, _, ms = string.partition(text, '.')
            else:
                text, _, ms = string.partition(text, ',')

            try:
                ms = int(ms) * 1000

            except ValueError:
                raise error.PyAsn1Error('bad sub-second time specification %s' % self)

        else:
            ms = 0

        if self._optionalMinutes and len(text) - self._yearsDigits == 6:
            text += '0000'
        elif len(text) - self._yearsDigits == 8:
            text += '00'

        try:
            dt = dateandtime.strptime(text, self._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S')

        except ValueError:
            raise error.PyAsn1Error('malformed datetime format %s' % self)

        return dt.replace(microsecond=ms, tzinfo=tzinfo)
314394
def rfc2822_datetime(s):
    
    date_tuple = parsedate(s)
    if date_tuple is None:
        return None
    return datetime.datetime(*date_tuple[:6]).replace(tzinfo=pytz.utc)
1259011
def _str_to_datetime(self, str_value):
        """"""
        try:
            ldt = [int(f) for f in str_value.split('-')]
            dt = datetime.datetime(*ldt)
        except (ValueError, TypeError):
            return None
        return dt
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)
1036733
def parse_time(s):
    
    result = None

    if "epoch" in s:
        epoch_time = float(s.rstrip().split(' ')[1][:-1])
        result = datetime.datetime.utcfromtimestamp(epoch_time)
    else:
        _, date_part, time_part = s.split(' ')
        year, mon, day = date_part.split('/')
        hour, minute, sec = time_part.split(':')
        result = datetime.datetime(*map(int, (year, mon, day, hour, minute, sec)))

    return result
116172
def to_datetime(time):
    ''''''
    if type(time) == IntType or type(time) == LongType:
        time = datetime.fromtimestamp(time // 1000)
    return time
239107
def datetime2gtd(time: Union[str, datetime.datetime, np.datetime64],
                 glon: Union[float, List[float], np.ndarray] = np.nan) -> Tuple[int, float, float]:
    
# %%
    T = np.atleast_1d(time)
    glon = np.asarray(glon)
    doy = np.empty_like(T, int)
    utsec = np.empty_like(T, float)
    stl = np.empty((T.size, *glon.shape))

    for i, t in enumerate(T):
        if isinstance(t, str):
            t = parse(t)
        elif isinstance(t, np.datetime64):
            t = t.astype(datetime.datetime)
        elif isinstance(t, (datetime.datetime, datetime.date)):
            pass
        else:
            raise TypeError('unknown time datatype {}'.format(type(t)))
# %% Day of year
        doy[i] = int(t.strftime('%j'))
# %% seconds since utc midnight
        utsec[i] = datetime2utsec(t)

        stl[i, ...] = utsec[i] / 3600. + glon / 15.

    return doy, utsec, stl
347918
def _convert_datetime_str(response):
    '''
    
    '''
    if response:
        return dict([(k, '{0}'.format(v)) if isinstance(v, datetime.date) else (k, v) for k, v in six.iteritems(response)])
    return None
1351459
def datetime_from_ldap(value):
    
    if not value:
        return None
    match = LDAP_DATETIME_RE.match(value)
    if not match:
        return None
    groups = match.groupdict()
    if groups['microsecond']:
        groups['microsecond'] = groups['microsecond'].ljust(6, '0')[:6]
    tzinfo = groups.pop('tzinfo')
    if tzinfo == 'Z':
        tzinfo = timezone.utc
    else:
        offset_mins = int(tzinfo[-2:]) if len(tzinfo) == 5 else 0
        offset = 60 * int(tzinfo[1:3]) + offset_mins
        if tzinfo[0] == '-':
            offset = - offset
        tzinfo = timezone.get_fixed_timezone(offset)
    kwargs = {k: int(v) for k, v in groups.items() if v is not None}
    kwargs['tzinfo'] = tzinfo
    return datetime.datetime(**kwargs)
1216892
def _convert_time(self, time_str):
        
        dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%SZ")
        return int(time.mktime(dt.utctimetuple()))
49770
def parse_time(time):
    """"""
    if isinstance(time, datetime.datetime):
        return time
    return datetime.datetime.strptime(time, DATETIME_FORMAT_OPENVPN)
1243253
def CopyToDateTimeStringISO8601(self):
    
    date_time_string = self.CopyToDateTimeString()
    if date_time_string:
      date_time_string = date_time_string.replace(' ', 'T')
      date_time_string = '{0:s}Z'.format(date_time_string)
    return date_time_string
1061130
def sqlalch_datetime(dt):
    """"""
    if isinstance(dt, str):
        return datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo=UTC)
    if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None:
        return dt.astimezone(UTC)
    return dt.replace(tzinfo=UTC)