当前位置: 首页>>代码示例>>Python>>正文


Python dates.date2num方法代码示例

本文整理汇总了Python中matplotlib.dates.date2num方法的典型用法代码示例。如果您正苦于以下问题:Python dates.date2num方法的具体用法?Python dates.date2num怎么用?Python dates.date2num使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.dates的用法示例。


在下文中一共展示了dates.date2num方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: interprete_data

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def interprete_data(payload, ident, stream, sensorid):
    """
    source:mqtt:
    """
    lines = payload.split(';') # for multiple lines send within one payload
    # allow for strings in payload !!
    array = [[] for elem in KEYLIST]
    keylist = identifier[sensorid+':keylist']
    multilist = identifier[sensorid+':multilist']
    for line in lines:
        data = line.split(',')
        timear = list(map(int,data[:7]))
        #log.msg(timear)
        time = datetime(timear[0],timear[1],timear[2],timear[3],timear[4],timear[5],timear[6])
        array[0].append(date2num(time))
        for idx, elem in enumerate(keylist):
            index = KEYLIST.index(elem)
            if not elem.endswith('time'):
                if elem in NUMKEYLIST:
                    array[index].append(float(data[idx+7])/float(multilist[idx]))
                else:
                    array[index].append(data[idx+7])

    return np.asarray([np.asarray(elem) for elem in array]) 
开发者ID:geomagpy,项目名称:magpy,代码行数:26,代码来源:collectormethods.py

示例2: send_command

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def send_command(self, ser,command,eol,hex=False):
            if hex:
                command = self.hexify_command(command,eol)
            else:
                command = eol+command+eol
            #print 'Command:  %s \n ' % command.replace(eol,'')
            sendtime = date2num(datetime.utcnow())
            #print "Sending"
            ser.write(command)
            #print "Received something - interpretation"
            response = self.lineread(ser,eol)
            #print "interprete", response
            receivetime = date2num(datetime.utcnow())
            meantime = np.mean([receivetime,sendtime])
            #print "Timediff", (receivetime-sendtime)*3600*24
            return response, num2date(meantime).replace(tzinfo=None) 
开发者ID:geomagpy,项目名称:magpy,代码行数:18,代码来源:callprotocol.py

示例3: _test_date2num_dst

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def _test_date2num_dst(date_range, tz_convert):
    # Timezones
    BRUSSELS = dateutil.tz.gettz('Europe/Brussels')
    UTC = mdates.UTC

    # Create a list of timezone-aware datetime objects in UTC
    # Interval is 0b0.0000011 days, to prevent float rounding issues
    dtstart = datetime.datetime(2014, 3, 30, 0, 0, tzinfo=UTC)
    interval = datetime.timedelta(minutes=33, seconds=45)
    interval_days = 0.0234375   # 2025 / 86400 seconds
    N = 8

    dt_utc = date_range(start=dtstart, freq=interval, periods=N)
    dt_bxl = tz_convert(dt_utc, BRUSSELS)

    expected_ordinalf = [735322.0 + (i * interval_days) for i in range(N)]
    actual_ordinalf = list(mdates.date2num(dt_bxl))

    assert actual_ordinalf == expected_ordinalf 
开发者ID:holzschu,项目名称:python3_ios,代码行数:21,代码来源:test_dates.py

示例4: __init__

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def __init__(self, dataset, rows=1, grid=True):
        # We need to handle a strategy being passed
        if isinstance(dataset, strategy.Strategy):
            self.strategy = dataset
            self.data_frame = self.strategy.dataset.data_frame
            self.realtime_data_frame = dataset.realtime_data_frame
        else: # Assume a dataset was passed
            self.strategy = None
            self.data_frame = dataset.data_frame
            self.realtime_data_frame = None
        self.data_frame.reset_index(inplace=True)
        date_conversion = lambda date: date2num(date.to_pydatetime())
        self.data_frame['DATE'] = self.data_frame['Date'].apply(date_conversion)
        self.rows = rows
        if grid:
            plt.rc('axes', grid=True)
            plt.rc('grid', color='0.75', linestyle='-', linewidth='0.2')
        self.current_figure = None
        self.figure_first_ax = None
        self.figure_rows = 1
        self.legend = []
        self.legend_labels = []
        self.add_figure(self.rows)
        self.logger = logger.Logger(self.__class__.__name__)
        self.logger.info('dataset: %s  rows: %s  grid: %s' %(dataset, rows, grid)) 
开发者ID:edouardpoitras,项目名称:NowTrade,代码行数:27,代码来源:figures.py

示例5: initializeLines

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def initializeLines(self, timestamps):
    for index in range(len(self.names)):
      print "initializing %s" % self.names[index]
      # graph = self.graphs[index]
      self.dates.append(deque([timestamps[index]] * WINDOW, maxlen=WINDOW))
      # print self.dates[index]
      # self.convertedDates.append(deque(
      #   [date2num(date) for date in self.dates[index]], maxlen=WINDOW
      # ))
      self.actualValues.append(deque([0.0] * WINDOW, maxlen=WINDOW))
      self.predictedValues.append(deque([0.0] * WINDOW, maxlen=WINDOW))

      actualPlot, = self.graphs[index].plot(
        self.dates[index], self.actualValues[index]
      )
      self.actualLines.append(actualPlot)
      predictedPlot, = self.graphs[index].plot(
        self.dates[index], self.predictedValues[index]
      )
      self.predictedLines.append(predictedPlot)
    self.linesInitialized = True 
开发者ID:htm-community,项目名称:nupic.critic,代码行数:23,代码来源:nupic_output.py

示例6: __loadTicksFromMongo

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def __loadTicksFromMongo(self,host,port,dbName,symbolName,startDatetimeStr,endDatetimeStr):
        """mid
        加载mongodb数据转换并返回数字格式的时间及价格
        """
        mongoConnection = MongoClient( host=host,port=port)
        collection = mongoConnection[dbName][symbolName]   

        startDate = dt.datetime.strptime(startDatetimeStr, '%Y-%m-%d %H:%M:%S')
        endDate = dt.datetime.strptime(endDatetimeStr, '%Y-%m-%d %H:%M:%S')  
        cx = collection.find({'datetime': {'$gte': startDate, '$lte': endDate}})    
        
        tickDatetimeNums = []
        tickPrices = []
        for d in cx:
            tickDatetimeNums.append(mpd.date2num(d['datetime']))
            tickPrices.append(d['lastPrice'])
        return tickDatetimeNums,tickPrices
    
    #---------------------------------------------------------------------- 
开发者ID:zhengwsh,项目名称:InplusTrader_Linux,代码行数:21,代码来源:monitor_tick_main.py

示例7: _process_hist

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def _process_hist(self, hist):
        """
        Get data from histogram, including bin_ranges and values.
        """
        self.cyclic = hist.get_dimension(0).cyclic
        x = hist.kdims[0]
        edges = hist.interface.coords(hist, x, edges=True)
        values = hist.dimension_values(1)
        hist_vals = np.array(values)
        xlim = hist.range(0)
        ylim = hist.range(1)
        is_datetime = isdatetime(edges)
        if is_datetime:
            edges = np.array([dt64_to_dt(e) if isinstance(e, np.datetime64) else e for e in edges])
            edges = date2num(edges)
            xlim = tuple(dt_to_int(v, 'D') for v in xlim)
        widths = np.diff(edges)
        return edges[:-1], hist_vals, widths, xlim+ylim, is_datetime 
开发者ID:holoviz,项目名称:holoviews,代码行数:20,代码来源:chart.py

示例8: toImage

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def toImage(self):
        from StringIO import StringIO
        import matplotlib.pyplot as plt
        from matplotlib.dates import date2num

        times = [date2num(datetime.fromtimestamp(dayavglistdict[0]['time'], pytz.utc).date()) for dayavglistdict in
                 self.results()]
        means = [dayavglistdict[0]['mean'] for dayavglistdict in self.results()]
        plt.plot_date(times, means, '|g-')

        plt.xlabel('Date')
        plt.xticks(rotation=70)
        plt.ylabel(u'Difference from 5-Day mean (\u00B0C)')
        plt.title('Sea Surface Temperature (SST) Anomalies')
        plt.grid(True)
        plt.tight_layout()

        sio = StringIO()
        plt.savefig(sio, format='png')
        return sio.getvalue() 
开发者ID:apache,项目名称:incubator-sdap-nexus,代码行数:22,代码来源:DailyDifferenceAverageSpark.py

示例9: _candlestick_ax

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def _candlestick_ax(df, ax):
    quotes = df.reset_index()
    quotes.loc[:, 'datetime'] = mdates.date2num(quotes.loc[:, 'datetime'].astype(dt.date))
    fplt.candlestick_ohlc(ax, quotes.values, width=0.4, colorup='red', colordown='green') 
开发者ID:X0Leon,项目名称:XQuant,代码行数:6,代码来源:chart.py

示例10: tim_slidupdate

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def tim_slidupdate(val):
        global cum_disp_flag
        timein = tslider.val
        timenearest = np.argmin(np.abs(mdates.date2num(imdates_dt)-timein))
        dstr = imdates_dt[timenearest].strftime('%Y/%m/%d')
#        axv.set_title('Time = %s'%(dstr))
        axv.set_title('%s (Ref: %s)'%(dstr, dstr_ref))
        newv = (cum[timenearest, :, :]-cum_ref)*mask
        newv = newv-np.nanmean(newv[refy1:refy2, refx1:refx2])
            
        cax.set_data(newv)
        cax.set_cmap(cmap)
        cax.set_clim(dmin, dmax)
        cbr.set_label('mm')
        cum_disp_flag = True

        pv.canvas.draw() 
开发者ID:yumorishita,项目名称:LiCSBAS,代码行数:19,代码来源:LiCSBAS_plot_ts.py

示例11: readGiopsIce

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def readGiopsIce(lat,lon,datenum):
    di = 0            
    for datei in datenum:
        print datei 
        dt0= datetime.strptime(datei, "%Y-%m-%d %H:%M:%S")
        dt1 = mdates.date2num(dt0)
#        dt2 = mdates.num2date(dt1)
        
#        print dt0,dt2
#        taxis.append(dt1)        
        
        dayStr = str(dt0.year)+str(dt0.month).rjust(2,'0')+str(dt0.day).rjust(2,'0')
#        print dayStr
        
        ficePath = "/home/xuj/work/project/novaFloat/iceData/"
        
        fname = ficePath+"giops_"+dayStr+"00_ice.nc"
        
        cfile = Dataset(fname,'r')
        
        aice = np.squeeze(cfile.variables["aice"][0,:,:])
        
    

    return giopsIce 
开发者ID:DFO-Ocean-Navigator,项目名称:Ocean-Data-Map-Project,代码行数:27,代码来源:usingFloat2extracCls4.py

示例12: _dt_to_float_ordinal

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def _dt_to_float_ordinal(dt):
    """
    Convert :mod:`datetime` to the Gregorian date as UTC float days,
    preserving hours, minutes, seconds and microseconds.  Return value
    is a :func:`float`.
    """
    if (isinstance(dt, (np.ndarray, Index, ABCSeries)
                   ) and is_datetime64_ns_dtype(dt)):
        base = dates.epoch2num(dt.asi8 / 1.0E9)
    else:
        base = dates.date2num(dt)
    return base


# Datetime Conversion 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:17,代码来源:_converter.py

示例13: _convert_1d

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def _convert_1d(values, unit, axis):
        def try_parse(values):
            try:
                return _dt_to_float_ordinal(tools.to_datetime(values))
            except Exception:
                return values

        if isinstance(values, (datetime, pydt.date)):
            return _dt_to_float_ordinal(values)
        elif isinstance(values, np.datetime64):
            return _dt_to_float_ordinal(tslibs.Timestamp(values))
        elif isinstance(values, pydt.time):
            return dates.date2num(values)
        elif (is_integer(values) or is_float(values)):
            return values
        elif isinstance(values, compat.string_types):
            return try_parse(values)
        elif isinstance(values, (list, tuple, np.ndarray, Index, ABCSeries)):
            if isinstance(values, ABCSeries):
                # https://github.com/matplotlib/matplotlib/issues/11391
                # Series was skipped. Convert to DatetimeIndex to get asi8
                values = Index(values)
            if isinstance(values, Index):
                values = values.values
            if not isinstance(values, np.ndarray):
                values = com.asarray_tuplesafe(values)

            if is_integer_dtype(values) or is_float_dtype(values):
                return values

            try:
                values = tools.to_datetime(values)
                if isinstance(values, Index):
                    values = _dt_to_float_ordinal(values)
                else:
                    values = [_dt_to_float_ordinal(x) for x in values]
            except Exception:
                values = _dt_to_float_ordinal(values)

        return values 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:42,代码来源:_converter.py

示例14: autoscale

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def autoscale(self):
        """
        Set the view limits to include the data range.
        """
        dmin, dmax = self.datalim_to_dt()
        if dmin > dmax:
            dmax, dmin = dmin, dmax

        # We need to cap at the endpoints of valid datetime

        # TODO(wesm): unused?

        # delta = relativedelta(dmax, dmin)
        # try:
        #     start = dmin - delta
        # except ValueError:
        #     start = _from_ordinal(1.0)

        # try:
        #     stop = dmax + delta
        # except ValueError:
        #     # The magic number!
        #     stop = _from_ordinal(3652059.9999999)

        dmin, dmax = self.datalim_to_dt()

        vmin = dates.date2num(dmin)
        vmax = dates.date2num(dmax)

        return self.nonsingular(vmin, vmax) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:32,代码来源:_converter.py

示例15: _convert_1d

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import date2num [as 别名]
def _convert_1d(values, unit, axis):
        def try_parse(values):
            try:
                return _dt_to_float_ordinal(tools.to_datetime(values))
            except Exception:
                return values

        if isinstance(values, (datetime, pydt.date)):
            return _dt_to_float_ordinal(values)
        elif isinstance(values, np.datetime64):
            return _dt_to_float_ordinal(tslib.Timestamp(values))
        elif isinstance(values, pydt.time):
            return dates.date2num(values)
        elif (is_integer(values) or is_float(values)):
            return values
        elif isinstance(values, compat.string_types):
            return try_parse(values)
        elif isinstance(values, (list, tuple, np.ndarray, Index)):
            if isinstance(values, Index):
                values = values.values
            if not isinstance(values, np.ndarray):
                values = com._asarray_tuplesafe(values)

            if is_integer_dtype(values) or is_float_dtype(values):
                return values

            try:
                values = tools.to_datetime(values)
                if isinstance(values, Index):
                    values = _dt_to_float_ordinal(values)
                else:
                    values = [_dt_to_float_ordinal(x) for x in values]
            except Exception:
                values = _dt_to_float_ordinal(values)

        return values 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:38,代码来源:_converter.py


注:本文中的matplotlib.dates.date2num方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。