The given string has one of the following formats
    YYYYMMDDhhmmssZ
    YYYYMMDDhhmmss+hhmm
    YYYYMMDDhhmmss-hhmm
    @return: a datetime object or None on error
6273
def asn1_generaltime_to_seconds(timestr):
    
    res = None
    timeformat = "%Y%m%d%H%M%S"
    try:
        res = datetime.strptime(timestr, timeformat + 'Z')
    except ValueError:
        try:
            res = datetime.strptime(timestr, timeformat + '%z')
        except ValueError:
            pass
    return res
23745
def convert_strtime_datetime(dt_str):
    
    dt, _, us = dt_str.partition(".")
    dt = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
    us = int(us.rstrip("Z"), 10)
    return dt + datetime.timedelta(microseconds=us)
868128
def parse_date(string, force_datetime=False):
    
    matches = DATE.match(string)
    if not matches:
        return None

    values = dict([
        (
            k,
            v if v[0] in '+-' else int(v)
        ) for k,v in matches.groupdict().items() if v and int(v)
    ])

    if 'timestamp' in values:
        value = datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(
            hours=int(values.get('offset_h', 0)),
            minutes=int(values.get('offset_m', 0)),
            seconds=int(values['timestamp']) / 1000.0
        )
        return value

    # I've made an assumption here, that a DateTime value will not
    # ever be YYYY-MM-DDT00:00:00, which is probably bad. I'm not
    # really sure how to handle this, other than to hard-code the
    # names of the field that are actually Date rather than DateTime.
    if len(values) > 3 or force_datetime:
        return datetime.datetime(**values)

    # Sometimes Xero returns Date(0+0000), so we end up with no
    # values. Return None for this case
    if not values:
        return None

    return datetime.date(**values)
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
1165964
def str_to_date(self):
        

        if hasattr(self, 'date'):
            return date(*list(map(int, self.date.split('-'))))
        else:
            return None
1247575
def str_to_datetime(dt_str, fmt='%Y-%m-%d %H:%M:%S'):
    
    d_time = datetime.datetime.strptime(dt_str, fmt)
    return d_time
1026435
def parse_datetime(src=None):
    """"""
    if src is None:
        return None
    string = src.replace('"', "")
    # parse timezone ourselves, since %z is not always supported
    # see: http://bugs.python.org/issue6641
    m = UTC_OFFSET_RE.match(string)
    if m:
        sign = 1 if m.group("sign") == "+" else -1
        tz_hours = sign * int(m.group("hours"))
        tz_minutes = sign * int(m.group("minutes"))
        offset = datetime.timedelta(hours=tz_hours, minutes=tz_minutes)
        string = string[:-6]
    else:
        # no explicit timezone
        offset = datetime.timedelta(0)
    if "AM" in string or "PM" in string:
        datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%d %I:%M:%S %p")
    else:
        datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
    return datetime_obj + offset
343609
def valueFromString(self, value, context=None):
        
        if value == 'now':
            return datetime.datetime.now().time()
        elif dateutil_parser:
            return dateutil_parser.parse(value).time()
        else:
            time_struct = time.strptime(value, self.defaultFormat())
            return datetime.time(time_struct.tm_hour,
                                 time_struct.tm_min,
                                 time_struct.tm_sec)
792907
def stringToDateTime(s, tzinfo=None):
    
    try:
        year = int(s[0:4])
        month = int(s[4:6])
        day = int(s[6:8])
        hour = int(s[9:11])
        minute = int(s[11:13])
        second = int(s[13:15])
        if len(s) > 15:
            if s[15] == 'Z':
                tzinfo = getTzid('UTC')
    except:
        raise ParseError("'{0!s}' is not a valid DATE-TIME".format(s))
    year = year and year or 2000
    if tzinfo is not None and hasattr(tzinfo,'localize'):  # PyTZ case
        return tzinfo.localize(datetime.datetime(year, month, day, hour, minute, second))
    return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)
1340455
def string_to_date(value):
    
    if isinstance(value, datetime.date):
        return value

    return dateutil.parser.parse(value).date()
1240275
def extract_datetime(cls, datetime_str):
        
        if not datetime_str:
            raise DateTimeFormatterException('datetime_str must a valid string')

        try:
            return cls._extract_timestamp(datetime_str, cls.DATETIME_FORMAT)
        except (TypeError, ValueError):
            raise DateTimeFormatterException('Invalid datetime string {}.'.format(datetime_str))
1098190
def str_to_datetime(timestamp, str_format='%Y-%m-%d_%H:%M:%S.fff'):
    
    date_time = datetime.strptime(timestamp.split('.')[0],
                                  str_format.split('.')[0])
    if '.' in timestamp:
        date_time += timedelta(seconds=eval('0.%s' % timestamp.split('.')[1]))
    if DEFAULT_TIMEZONE_AWARE:
        date_time = date_time.replace(
            tzinfo=psycopg2.tz.FixedOffsetTimezone(
                offset=DEFAULT_TIMEZONE * 60, name=None))
    return date_time
1337481
def formatIBDatetime(dt) -> str:
    
    if not dt:
        s = ''
    elif isinstance(dt, datetime.datetime):
        if dt.tzinfo:
            # convert to local system timezone
            dt = dt.astimezone()
        s = dt.strftime('%Y%m%d %H:%M:%S')
    elif isinstance(dt, datetime.date):
        s = dt.strftime('%Y%m%d 23:59:59')
    else:
        s = dt
    return s
297615
def stringToDateTime(s, tzinfo=None):
    """"""
    try:
        year = int(s[0:4])
        month = int(s[4:6])
        day = int(s[6:8])
        hour = int(s[9:11])
        minute = int(s[11:13])
        second = int(s[13:15])
        if len(s) > 15:
            if s[15] == 'Z':
                tzinfo = utc
    except:
        raise ParseError("'%s' is not a valid DATE-TIME" % s)
    year = year and year or 2000
    return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)
968076
def get_datetime(strings: Sequence[str],
                 prefix: str,
                 datetime_format_string: str,
                 ignoreleadingcolon: bool = False,
                 precedingline: str = "") -> Optional[datetime.datetime]:
    
    x = get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon,
                   precedingline=precedingline)
    if len(x) == 0:
        return None
    # For the format strings you can pass to datetime.datetime.strptime, see
    # http://docs.python.org/library/datetime.html
    # A typical one is "%d-%b-%Y (%H:%M:%S)"
    d = datetime.datetime.strptime(x, datetime_format_string)
    return d
280367
def parseIBDatetime(s):
    
    if len(s) == 8:
        # YYYYmmdd
        y = int(s[0:4])
        m = int(s[4:6])
        d = int(s[6:8])
        dt = datetime.date(y, m, d)
    elif s.isdigit():
        dt = datetime.datetime.fromtimestamp(
            int(s), datetime.timezone.utc)
    else:
        dt = datetime.datetime.strptime(s, '%Y%m%d  %H:%M:%S')
    return dt
1111245
def datetime_from_ISO_string(s):
    
    try:
        return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
    except ValueError:
        try:
            return datetime.datetime.strptime(s, '%Y-%m-%d')
        except ValueError:
            return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f')