输入是交易所规定的时间,返回真实时间*适用于通达信的时间转换

    Arguments:
        trade_datetime {[type]} -- [description]

    Returns:
        [type] -- [description]
438927
def QA_util_future_to_realdatetime(trade_datetime):
    
    if len(str(trade_datetime)) == 19:
        dt = datetime.datetime.strptime(
            str(trade_datetime)[0:19],
            '%Y-%m-%d %H:%M:%S'
        )
        return dt if dt.time(
        ) < datetime.time(21,
                          0) else QA_util_get_last_datetime(dt,
                                                            1)
    elif len(str(trade_datetime)) == 16:
        dt = datetime.datetime.strptime(
            str(trade_datetime)[0:16],
            '%Y-%m-%d %H:%M'
        )
        return dt if dt.time(
        ) < datetime.time(21,
                          0) else QA_util_get_last_datetime(dt,
                                                            1)
1167071
def QA_util_get_pre_trade_date(cursor_date, n=1):
    

    cursor_date = QA_util_format_date2str(cursor_date)
    if cursor_date in trade_date_sse:
        return QA_util_date_gap(cursor_date, n, "lt")
    real_aft_trade_date = QA_util_get_real_date(cursor_date)
    return QA_util_date_gap(real_aft_trade_date, n, "lt")
997970
def dateTime(arg):
  
  l = len(arg)
  if l is 1:
    dt = arg[0]
    typed = type(dt)
    if typed is datetime.datetime:
      return dt
    if typed in (tuple, list) and len(dt) in [5, 6, 7]:
      return datetime.datetime(*dt)
  if l is 2:
    date = time = None
    typeArg0 = type(arg[0])
    typeArg1 = type(arg[1])
    if typeArg0 in STR_TYPES:
      return datetime.datetime.strptime(arg[0], arg[1])
    if typeArg0 is datetime.date:
      d = arg[0]
      date = [d.year, d.month, d.day]
    if typeArg0 in (tuple, list):
      date = arg[0]
    if typeArg1 is datetime.time:
      t = arg[1]
      time = [t.hour, t.minute, t.second, t.microsecond]
    if typeArg1 in (tuple, list):
      time = arg[1]
    return datetime.datetime(*date + time)
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))
724670
def rate_timestamp(self, rate_timestamp):
        
        if rate_timestamp is not None:
            if isinstance(rate_timestamp, (str, type_check)):
                rate_timestamp = parse(rate_timestamp).replace(tzinfo=pytz.utc)
            if type(rate_timestamp) == date:
                rate_timestamp = datetime.combine(rate_timestamp, datetime.min.time()).replace(tzinfo=pytz.utc)
            if not rate_timestamp.tzinfo:
                raise ValueError('Cannot set an FX rate timestamp without a timezone')
            self._rate_timestamp = rate_timestamp
445597
def unpack_datetime(self, data):
        

        if data is None:
            return None

        try:
            value = CIMDateTime(data)
        except ValueError as exc:
            raise CIMXMLParseError(
                _format("Invalid datetime value: {0!A} ({1})", data, exc),
                conn_id=self.conn_id)
        return value
681080
def QA_util_get_next_trade_date(cursor_date, n=1):
    

    cursor_date = QA_util_format_date2str(cursor_date)
    if cursor_date in trade_date_sse:
        # 如果指定日期为交易日
        return QA_util_date_gap(cursor_date, n, "gt")
    real_pre_trade_date = QA_util_get_real_date(cursor_date)
    return QA_util_date_gap(real_pre_trade_date, n, "gt")
1020929
def QA_fetch_stock_day_full_adv(date):
    '''
    
    '''
    # 🛠 todo 检查日期data参数
    res = QA_fetch_stock_full(date, 'pd')
    if res is None:
        print("QA Error QA_fetch_stock_day_full_adv parameter date=%s call QA_fetch_stock_full return None" % (date))
        return None
    else:
        res_set_index = res.set_index(['date', 'code'])
        # if res_set_index is None:
        #     print("QA Error QA_fetch_stock_day_full set index 'date, code' return None")
        return QA_DataStruct_Stock_day(res_set_index)
1091059
def hold_time(self, datetime=None):
        

        def weights(x):
            if sum(x['amount']) != 0:
                return pd.Timestamp(self.datetime
                                   ) - pd.to_datetime(x.datetime.max())
            else:
                return np.nan

        if datetime is None:
            return self.history_table.set_index(
                'datetime',
                drop=False
            ).sort_index().groupby('code').apply(weights).dropna()
        else:
            return self.history_table.set_index(
                'datetime',
                drop=False
            ).sort_index().loc[:datetime].groupby('code').apply(weights
                                                               ).dropna()
1259315
def is_tradetime_now():
    
    cal = Calendar('china.sse')
    now_time = time.localtime()
    today = Date(now_time[0], now_time[1], now_time[2])
    if not cal.isBizDay(today):
        return False
    now = (now_time.tm_hour, now_time.tm_min, now_time.tm_sec)
    if (9, 15, 0) <= now <= (11, 30, 0) or (13, 0, 0) <= now <= (15, 0, 0):
        return True
    return False
1254793
def cast_datetime_filter(value):
    
    if isinstance(value, str):
        dtime = parse_datetime(value)

    elif isinstance(value, datetime):
        dtime = value
    else:
        raise ValueError('Received value of type {0}'.format(type(value)))

    return dtime.isoformat()
909862
def to_timestamp(self, value):
        
        if isinstance(value, (six.integer_types, float, six.string_types)):
            try:
                return int(value)
            except ValueError:
                value = self.datetime_str_to_datetime(value)

        if isinstance(value, datetime.datetime):
            if timezone.is_aware(value):
                value = timezone.localtime(value, timezone.utc)
            return self._datetime_to_timestamp(value)

        raise exceptions.ValidationError(
            "Unable to convert value: '%s' to timestamp" % value,
            code="invalid_timestamp"
        )
1147367
def timestamp_after_timestamp(self, timestamp=None, seconds=0, minutes=0, hours=0, days=0):
        
        #1. 默认时间戳为当前时间
        timestamp = self.get_current_timestamp() if timestamp is None else timestamp
        #2. 先转换为datetime
        d1 = datetime.datetime.fromtimestamp(timestamp)
        #3. 根据相关时间得到datetime对象并相加给定时间戳的时间
        d2 = d1 + datetime.timedelta(seconds=int(seconds), minutes=int(minutes), hours=int(hours), days=int(days))
        #4. 返回某时间后的时间戳
        return int(time.mktime(d2.timetuple()))
604423
def trade_day(dt, cal='US'):
    
    from xone import calendar

    dt = pd.Timestamp(dt).date()
    return calendar.trading_dates(start=dt - pd.Timedelta('10D'), end=dt, calendar=cal)[-1]
932214
def get_cgi_parameter_datetime(form: cgi.FieldStorage,
                               key: str) -> Optional[datetime.datetime]:
    
    try:
        s = get_cgi_parameter_str(form, key)
        if not s:
            # if you dateutil.parser.parse() an empty string,
            # you get today's date
            return None
        d = dateutil.parser.parse(s)
        if d.tzinfo is None:  # as it will be
            d = d.replace(tzinfo=dateutil.tz.tzlocal())
        return d
    except ValueError:
        return None
732236
def _date_to_datetime(value):
  
  if not isinstance(value, datetime.date):
    raise TypeError('Cannot convert to datetime expected date value; '
                    'received %s' % value)
  return datetime.datetime(value.year, value.month, value.day)
185930
def tgread_date(self):
        
        value = self.read_int()
        if value == 0:
            return None
        else:
            return datetime.fromtimestamp(value, tz=timezone.utc)