100 days of code: Day 36 - datetime

Last modified on 2020-07-15

Source: 100-days-of-code.

I want to add the capability of generating graphs to my datetag.py module. The x-axis will use calendar dates and the y-axis will plot measurements.

First step is to convert the date strings retrieved from a Python dictionary into date objects using the datetime module included in the Python standard library. I created a small program - datetimes.py - to experiment …

import datetime as dt

dictionary = {'2015-07-29': '60.7', '2015-07-28': '60.6', 
    '2015-07-27': '60.7', '2015-07-26': '61.2'}

class Graph:
    """
    Create a graph plotting dates on the x-axis and measurements on the y-axis.
    """

    def __init__(self, dictionary):
        #title, xlabel, x_axis, ylabel, y_axis):
        """Initialize source data attribute."""
        self.data = dictionary

    def x_axis(self):
        """Create a list of datetime objects for the x-axis."""
        dates = []
        for key in self.data.keys():
            dates.append(key)
        # Create date objects in the syntax `datetime.date(Y, M, D)`.
        x = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates]
        return x

my_graph = Graph(dictionary)
print(my_graph.x_axis())

Run …

$ ./datetimes.py 
[datetime.date(2015, 7, 29), datetime.date(2015, 7, 28), datetime.date(2015, 7, 27), datetime.date(2015, 7, 26)]

Happy hacking!