Here's a Python script that charts dates and times entered from a list, where the time is in the form of time of day (e.g., 05:30):
python
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
# List of dates and times
data = [
('2023-05-01', '05:30'),
('2023-05-02', '07:45'),
('2023-05-03', '12:00'),
('2023-05-04', '15:20'),
('2023-05-05', '18:10')
]
# Convert dates and times to datetime objects
dates = [datetime.strptime(date + ' ' + time, '%Y-%m-%d %H:%M') for date, time in data]
# Create a figure and axis
fig, ax = plt.subplots(figsize=(10, 6))
# Plot the dates and times as points
ax.plot(dates, [1] * len(dates), 'o')
# Set the x-axis label and format
ax.set_xlabel('Date and Time')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
# Set the y-axis label and limits
ax.set_ylabel('Event')
ax.set_yticks([])
# Rotate the x-axis labels for better readability
plt.xticks(rotation=45)
# Add a title to the chart
plt.title('Date and Time Chart')
# Adjust the layout and display the chart
plt.tight_layout()
plt.show()
This script does the following:
We import the necessary libraries: matplotlib.pyplot for creating the chart, matplotlib.dates for formatting dates on the x-axis, and datetime for handling date and time objects.
We define a list called data that contains tuples of dates and times in the format ('YYYY-MM-DD', 'HH:MM').
We convert the dates and times from the data list into datetime objects using a list comprehension and the datetime.strptime() function. This step combines the date and time strings into a single datetime object.
We create a figure and axis using plt.subplots() to hold the chart.
We plot the dates and times as points on the chart using ax.plot(). We pass the list of datetime objects as the x-coordinates and a list of ones ([1] * len(dates)) as the y-coordinates to create a horizontal line of points.
We set the x-axis label using ax.set_xlabel() and format the x-axis labels using mdates.DateFormatter() to display the date and time in the desired format.
We set the y-axis label using ax.set_ylabel() and remove the y-axis ticks using ax.set_yticks([]) since we don't have any meaningful y-values.
We rotate the x-axis labels by 45 degrees using plt.xticks(rotation=45) for better readability.
We add a title to the chart using plt.title().
Finally, we adjust the layout using plt.tight_layout() and display the chart using plt.show().
When you run this script, it will generate a chart with the dates and times plotted as points on the x-axis. The x-axis labels will show the date and time in the format 'YYYY-MM-DD HH:MM'.