2

I am writing a python script that produces a bar graph of data between two dates specified by the user

For example here the user enters 30 November and 4 December

import datetime as dt
dateBegin = dt.date(2012,11,30)
dateEnd = dt.date(2012,12,4)

Is there a way to return an array of the dates between dateBegin and dateEnd? What I want is something like [30, 1, 2, 3, 4]. Any suggestions?

1 Answer 1

2

Sure! You are looking for 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()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.