python date2num_Python dates.num2date方法代码示例

本文详细介绍了Python中matplotlib.dates模块的num2date方法,提供14个实用代码示例,展示如何将日期数字转换为datetime对象。涉及的场景包括时间戳处理、数据读取、日期定位器、时间轴调整等,适用于需要进行日期转换的Matplotlib用户。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

示例1: send_command

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [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,

示例2: test_yearlocator_pytz

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def test_yearlocator_pytz():

import pytz

tz = pytz.timezone('America/New_York')

x = [tz.localize(datetime.datetime(2010, 1, 1))

+ datetime.timedelta(i) for i in range(2000)]

locator = mdates.AutoDateLocator(interval_multiples=True, tz=tz)

locator.create_dummy_axis()

locator.set_view_interval(mdates.date2num(x[0])-1.0,

mdates.date2num(x[-1])+1.0)

np.testing.assert_allclose([733408.208333, 733773.208333, 734138.208333,

734503.208333, 734869.208333,

735234.208333, 735599.208333], locator())

expected = ['2009-01-01 00:00:00-05:00',

'2010-01-01 00:00:00-05:00', '2011-01-01 00:00:00-05:00',

'2012-01-01 00:00:00-05:00', '2013-01-01 00:00:00-05:00',

'2014-01-01 00:00:00-05:00', '2015-01-01 00:00:00-05:00']

st = list(map(str, mdates.num2date(locator(), tz=tz)))

assert st == expected

开发者ID:holzschu,项目名称:python3_ios,代码行数:22,

示例3: readGiopsIce

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [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,

示例4: adjust_xlim

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def adjust_xlim(ax, timemax, xlabel=False):

xlim = mdates.num2date(ax.get_xlim())

update = False

# remove timezone awareness to make them comparable

timemax = timemax.replace(tzinfo=None)

xlim[0] = xlim[0].replace(tzinfo=None)

xlim[1] = xlim[1].replace(tzinfo=None)

if timemax > xlim[1] - timedelta(minutes=30):

xmax = xlim[1] + timedelta(hours=6)

update = True

if update:

ax.set_xlim([xlim[0], xmax])

for spine in ax.spines.values():

ax.draw_artist(spine)

ax.draw_artist(ax.xaxis)

if xlabel:

ax.xaxis.set_minor_locator(mdates.AutoDateLocator())

ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M\n'))

ax.xaxis.set_major_locator(mdates.DayLocator())

ax.xaxis.set_major_formatter(mdates.DateFormatter('\n%b %d'))

开发者ID:jxx123,项目名称:simglucose,代码行数:25,

示例5: test_drange

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def test_drange():

"""

This test should check if drange works as expected, and if all the

rounding errors are fixed

"""

start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC)

end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)

delta = datetime.timedelta(hours=1)

# We expect 24 values in drange(start, end, delta), because drange returns

# dates from an half open interval [start, end)

assert_equal(24, len(mdates.drange(start, end, delta)))

# if end is a little bit later, we expect the range to contain one element

# more

end = end + datetime.timedelta(microseconds=1)

assert_equal(25, len(mdates.drange(start, end, delta)))

# reset end

end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)

# and tst drange with "complicated" floats:

# 4 hours = 1/6 day, this is an "dangerous" float

delta = datetime.timedelta(hours=4)

daterange = mdates.drange(start, end, delta)

assert_equal(6, len(daterange))

assert_equal(mdates.num2date(daterange[-1]), end - delta)

开发者ID:miloharper,项目名称:neural-network-animation,代码行数:28,

示例6: __call__

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def __call__(self, x, pos=0):

'Return the label for time x at position pos'

ind = int(np.round(x))

if ind >= len(self.dates) or ind < 0:

return ''

return num2date(self.dates[ind]).strftime(self.fmt)

开发者ID:holzschu,项目名称:python3_ios,代码行数:9,

示例7: test_drange

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def test_drange():

"""

This test should check if drange works as expected, and if all the

rounding errors are fixed

"""

start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC)

end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)

delta = datetime.timedelta(hours=1)

# We expect 24 values in drange(start, end, delta), because drange returns

# dates from an half open interval [start, end)

assert len(mdates.drange(start, end, delta)) == 24

# if end is a little bit later, we expect the range to contain one element

# more

end = end + datetime.timedelta(microseconds=1)

assert len(mdates.drange(start, end, delta)) == 25

# reset end

end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)

# and tst drange with "complicated" floats:

# 4 hours = 1/6 day, this is an "dangerous" float

delta = datetime.timedelta(hours=4)

daterange = mdates.drange(start, end, delta)

assert len(daterange) == 6

assert mdates.num2date(daterange[-1]) == (end - delta)

开发者ID:holzschu,项目名称:python3_ios,代码行数:28,

示例8: getTickDatetimeByXPosition

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def getTickDatetimeByXPosition(self,xAxis):

"""mid

根据传入的x轴坐标值,返回其所代表的时间

"""

tickDatetimeRet = xAxis

minYearDatetimeNum = mpd.date2num(dt.datetime(1900,1,1))

if(xAxis > minYearDatetimeNum):

tickDatetime = mpd.num2date(xAxis).astimezone(pytz.timezone('utc'))

if(tickDatetime.year >=1900):

tickDatetimeRet = tickDatetime

return tickDatetimeRet

开发者ID:zhengwsh,项目名称:InplusTrader_Linux,代码行数:13,

示例9: __getTickDatetimeByXPosition

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def __getTickDatetimeByXPosition(self,xAxis):

"""mid

默认计算方式,用datetimeNum标记x轴

根据某个view中鼠标所在位置的x坐标获取其所在tick的time,xAxis可以是index,也可是一datetime转换而得到的datetimeNum

return:str

"""

tickDatetimeRet = xAxis

minYearDatetimeNum = mpd.date2num(dt.datetime(1900,1,1))

if(xAxis > minYearDatetimeNum):

tickDatetime = mpd.num2date(xAxis).astimezone(pytz.timezone('utc'))

if(tickDatetime.year >=1900):

tickDatetimeRet = tickDatetime

return tickDatetimeRet

#----------------------------------------------------------------------

开发者ID:zhengwsh,项目名称:InplusTrader_Linux,代码行数:17,

示例10: plotYearly

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def plotYearly(dictframe, ax, uncertainty, color='#0072B2'):

if ax is None:

figY = plt.figure(facecolor='w', figsize=(10, 6))

ax = figY.add_subplot(111)

else:

figY = ax.get_figure()

##

# Find the max index for an entry of each month

##

months = dictframe.ds.dt.month

ind = []

for month in range(1,13):

ind.append(max(months[months == month].index.tolist()))

##

# Plot from the minimum of those maximums on (this will almost certainly result in only 1 year plotted)

##

ax.plot(dictframe['ds'][min(ind):], dictframe['yearly'][min(ind):], ls='-', c=color)

if uncertainty:

ax.fill_between(dictframe['ds'].values[min(ind):], dictframe['yearly_lower'][min(ind):], dictframe['yearly_upper'][min(ind):], color=color, alpha=0.2)

ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)

months = MonthLocator(range(1, 13), bymonthday=1, interval=2)

ax.xaxis.set_major_formatter(FuncFormatter(

lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))

ax.xaxis.set_major_locator(months)

ax.set_xlabel('Day of year')

ax.set_ylabel('yearly')

figY.tight_layout()

return figY

开发者ID:CollinRooney12,项目名称:htsprophet,代码行数:31,

示例11: plot_date_bars

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def plot_date_bars(bin_data, bin_edges, title, ylabel, fname):

"""

Semi-generic function to plot a bar graph, x-label is fixed to "date" and the

x-ticks are formatted accordingly.

To plot a histogram, the histogram data must be calculated manually outside

this function, either manually or using :py:func`numpy.histogram`.

:param bin_data: list of data for each bin

:param bin_edges: list of bin edges (:py:class:`datetime.date` objects), its

length must be ``len(data)+1``

:param title: title of the plot

:param ylabel: label of y-axis

:param fname: output file name

"""

import matplotlib.pyplot as plt

from matplotlib.dates import date2num, num2date

from matplotlib import ticker

plt.figure() # clear previous figure

plt.title(title)

plt.xlabel("date")

plt.ylabel(ylabel)

# plot the bars, width of the bins is assumed to be fixed

plt.bar(date2num(bin_edges[:-1]), bin_data, width=date2num(bin_edges[1]) - date2num(bin_edges[0]))

# x-ticks formatting

plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda numdate, _: num2date(numdate).strftime('%Y-%m-%d')))

plt.gcf().autofmt_xdate()

plt.tick_params(axis="x", which="both", direction="out")

plt.xticks([date2num(ts) for ts in bin_edges if ts.month % 12 == 1])

plt.savefig(fname, papertype="a4")

开发者ID:lahwaacz,项目名称:wiki-scripts,代码行数:36,

示例12: main

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def main(args):

_, fetch = load_dataset(SP500, shuffle=False)

dates, returns = fetch()

init_rng_key, sample_rng_key = random.split(random.PRNGKey(args.rng_seed))

model_info = initialize_model(init_rng_key, model, model_args=(returns,))

init_kernel, sample_kernel = hmc(model_info.potential_fn, algo='NUTS')

hmc_state = init_kernel(model_info.param_info, args.num_warmup, rng_key=sample_rng_key)

hmc_states = fori_collect(args.num_warmup, args.num_warmup + args.num_samples, sample_kernel, hmc_state,

transform=lambda hmc_state: model_info.postprocess_fn(hmc_state.z),

progbar=False if "NUMPYRO_SPHINXBUILD" in os.environ else True)

print_results(hmc_states, dates)

fig, ax = plt.subplots(1, 1)

dates = mdates.num2date(mdates.datestr2num(dates))

ax.plot(dates, returns, lw=0.5)

# format the ticks

ax.xaxis.set_major_locator(mdates.YearLocator())

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

ax.xaxis.set_minor_locator(mdates.MonthLocator())

ax.plot(dates, jnp.exp(hmc_states['s'].T), 'r', alpha=0.01)

legend = ax.legend(['returns', 'volatility'], loc='upper right')

legend.legendHandles[1].set_alpha(0.6)

ax.set(xlabel='time', ylabel='returns', title='Volatility of S&P500 over time')

plt.savefig("stochastic_volatility_plot.pdf")

plt.tight_layout()

开发者ID:pyro-ppl,项目名称:numpyro,代码行数:29,

示例13: ploteasy

​点赞 4

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def ploteasy(stream):

'''

DEFINITION:

Plots all data in stream. That's it.

This function has no formatting options whatsoever.

Very useful for quick & easy data evaluation.

PARAMETERS:

Variables:

- stream: (DataStream object) Stream to plot

RETURNS:

- plot: (Pyplot plot) Returns plot as plt.show()

EXAMPLE:

>>> ploteasy(somedata)

'''

keys = stream._get_key_headers(numerical=True)

if len(keys) > 9:

keys = keys[:8]

try:

sensorid = stream.header['SensorID']

except:

sensorid = ''

try:

datadate = datetime.strftime(num2date(stream[0].time),'%Y-%m-%d')

except:

datadate = datetime.strftime(num2date(stream.ndarray[0][0]),'%Y-%m-%d')

plottitle = "%s (%s)" % (sensorid,datadate)

logger.info("Plotting keys:", keys)

plot_new(stream, keys,

confinex = True,

plottitle = plottitle)

#####################################################################

# #

# MAIN PLOTTING FUNCTIONS #

# (for plotting geomagnetic data) #

# #

#####################################################################

开发者ID:geomagpy,项目名称:magpy,代码行数:44,

示例14: interpHovmoller

​点赞 4

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import num2date [as 别名]

def interpHovmoller(self,target_track,window=4,align='backward'):

r"""

Creates storm-centered interpolated data in polar coordinates for each timestep, and averages azimuthally to create a hovmoller.

target_track = dict

dict of either archer or hurdat data (contains lat, lon, time/date)

window = hours

sets window in hours relative to the time of center pass for interpolation use.

"""

#Store the dataframe containing recon data

tmpRecon = self.dfRecon.copy()

#Sets window as a timedelta object

window = timedelta(seconds=int(window*3600))

#Error check for time dimension name

if 'time' not in target_track.keys():

target_track['time']=target_track['date']

#Find times of all center passes

centerTimes = tmpRecon[tmpRecon['iscenter']==1]['time']

#Data is already centered on center time, so shift centerTimes to the end of the window

spaceInterpTimes = [t+window/2 for t in centerTimes]

#Takes all times within track dictionary that fall between spaceInterpTimes

trackTimes = [t for t in target_track['time'] if min(spaceInterpTimes)

#Iterate through all data surrounding a center pass given the window previously specified, and create a polar

#grid for each

start_time = dt.now()

print("--> Starting interpolation")

spaceInterpData={}

for time in spaceInterpTimes:

#Temporarily set dfRecon to this centered subset window

self.dfRecon = tmpRecon[(tmpRecon['time']>time-window) & (tmpRecon['time']<=time)]

print(time)

grid_rho, grid_phi, grid_z_pol = self.interpPol() #Create polar centered grid

grid_azim_mean = np.mean(grid_z_pol,axis=0) #Average azimuthally

spaceInterpData[time] = grid_azim_mean #Append data for this time step to dictionary

#Sets dfRecon back to original full data

self.dfRecon = tmpRecon

reconArray = np.array([i for i in spaceInterpData.values()])

#Interpolate over every half hour

newTimes = np.arange(mdates.date2num(trackTimes[0]),mdates.date2num(trackTimes[-1])+1e-3,1/48)

oldTimes = mdates.date2num(spaceInterpTimes)

reconTimeInterp=np.apply_along_axis(lambda x: np.interp(newTimes,oldTimes,x),

axis=0,arr=reconArray)

time_elapsed = dt.now() - start_time

tsec = str(round(time_elapsed.total_seconds(),2))

print(f"--> Completed interpolation ({tsec} seconds)")

#Output RMW and hovmoller data and store as an attribute in the object

self.rmw = grid_rho[0,np.nanargmax(reconTimeInterp,axis=1)]

self.Hovmoller = {'time':mdates.num2date(newTimes),'radius':grid_rho[0,:],'hovmoller':reconTimeInterp}

return self.Hovmoller

开发者ID:tropycal,项目名称:tropycal,代码行数:61,

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值