I would like to loop over a range of datetime values in order to use it as my x-axis in a matplotlib Graph in Python.
Here's my code :
import matplotlib.pyplot as plt
from datetime import datetime
dates = [
datetime(2022, 6, 21, 0),
datetime(2022, 6, 21, 1),
datetime(2022, 6, 21, 2),
datetime(2022, 6, 21, 3),
...
datetime(2022, 6, 23, 10),
datetime(2022, 6, 23, 11),
datetime(2022, 6, 23, 12),
...
datetime(2022, 6, 25, 21),
datetime(2022, 6, 25, 22),
datetime(2022, 6, 25, 23)
]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, ..., 168]
# plotting the points
plt.plot(dates, y)
plt.show()
How can I use a loop in order to avoid entering datetimes manually ?
Imagine for example that I want to use hourly datetime for a whole week, this would mean 168 datetimes into dates = []
. Not efficient at all !
Do you have any ideas ?
Thanks and regards,
CodePudding user response:
This should do the trick:
from datetime import datetime, timedelta
start_date = datetime(2022, 6, 21, 0)
end_date = datetime(2022, 6, 25, 23)
hour = timedelta(hours=1)
days = []
while start_date <= end_date:
days.append(start_date)
start_date = hour
print(days)
CodePudding user response:
I usually do this :
from datetime import datetime, timedelta
dates = [datetime(2022,6,21,0) timedelta(hours=h) for h in range(168)]