Appendix C. Dates and Times
As in the majority of scientific disciplines, dates and times play an important role in finance. This appendix introduces different aspects of this topic when it comes to Python programming. It cannot, of course, not be exhaustive. However, it provides an introduction into the main areas of the Python ecosystem that support the modeling of date and time information.
Python
The datetime module from the Python standard library allows for the implementation of the most important date and time-related tasks.[85] We start by importing the module:
In[1]:importdatetimeasdt
Two different functions provide the exact current date and time:
In[2]:dt.datetime.now()
Out[2]: datetime.datetime(2014, 9, 14, 19, 22, 24, 366619)
In[3]:to=dt.datetime.today()to
Out[3]: datetime.datetime(2014, 9, 14, 19, 22, 24, 491234)
The resulting object is a datetime object:
In[4]:type(to)
Out[4]: datetime.datetime
The method weekday provides the number for the day of the week, given a datetime object:
In[5]:dt.datetime.today().weekday()# zero-based numbering; 0 = Monday
Out[5]: 6
Such an object can, of course, be directly constructed:
In[6]:d=dt.datetime(2016,10,31,10,5,30,500000)d
Out[6]: datetime.datetime(2016, 10, 31, 10, 5, 30, 500000)
In[7]:d
Out[7]: 2016-10-31 10:05:30.500000
In[8]:str(d)
Out[8]: '2016-10-31 10:05:30.500000'
From such an object you can easily extract, for example, year, month, day information, and so forth:
In[9]:d.year
Out[9]: 2016
In[10]:d.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access