我正在编写一个python脚本,用于生成用户指定的两个日期之间的数据条形图
例如,用户输入11月30日和12月4日
将日期时间导入为dt
dateBegin = dt.date(2012,11,30)
dateEnd = dt.date(2012,12,4)
有没有办法在dateBegin和dateEnd之间返回日期数组? 我想要的是[30,1,2,3,4]。有什么建议吗?
答案 0 :(得分:2)
当然!您正在寻找matplotlib.dates.drange:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import datetime as DT
dates = mdates.num2date(mdates.drange(DT.datetime(2012, 11, 30),
DT.datetime(2012, 12, 4),
DT.timedelta(days=1)))
print(dates)
# [datetime.datetime(2012, 11, 30, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x8c8f8ec>), datetime.datetime(2012, 12, 1, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x8c8f8ec>), datetime.datetime(2012, 12, 2, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x8c8f8ec>), datetime.datetime(2012, 12, 3, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x8c8f8ec>)]
vals = np.random.randint(10, size=len(dates))
fig, ax = plt.subplots()
ax.bar(dates, vals, align='center')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.xticks(rotation=25)
ax.set_xticks(dates)
plt.show()