## 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``]:` `import` `datetime` `as` `dt``

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``]:` `print` `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``.``

Get Python for Finance now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.