Working with datetimes

Intermediate Python for Finance

Kennedy Behrman

Data Engineer, Author, Founder

Datetime attributes

now.year
now.month
now.day
2019
11
13
now.hour
now.minute
now.second
22
34
56
Intermediate Python for Finance

Comparing datetimes

equals ==

less than <

more than >

Intermediate Python for Finance

Comparing datetimes

from datetime import datetime
asian_crisis = datetime(1997, 7, 2)
world_mini_crash = datetime(1997, 10, 27)
asian_crisis > world_mini_crash
False
asian_crisis < world_mini_crash
True
Intermediate Python for Finance

Comparing datetimes

asian_crisis = datetime(1997, 7, 2)
world_mini_crash = datetime(1997, 10, 27)
text = "10/27/1997"
format_str =  "%m/%d/%Y"
sell_date = datetime.strptime(text, format_str)
sell_date == world_mini_crash
True
Intermediate Python for Finance

Difference between datetimes

  • Compare with <, >, or ==.
  • Subtraction returns a timedelta object.
  • timedelta attributes: weeks, days, minutes, seconds, microseconds
Intermediate Python for Finance

Difference between datetimes

delta = world_mini_crash - asian_crisis
type(delta)
datetime.timedelta
delta.days
117
Intermediate Python for Finance

Creating relative datetimes

dt
datetime.datetime(2019, 1, 14, 0, 0)
datetime(dt.year, dt.month, dt.day - 7)
datetime.datetime(2019, 1, 7, 0, 0)
datetime(dt.year, dt.month, dt.day - 15)
ValueError                                Traceback (most recent call last)
<ipython-input-28-804001f45cdb> in <module>()
-> 1 datetime(dt.year, dt.month, dt.day - 15)
ValueError: day is out of range for month
Intermediate Python for Finance

Creating relative datetimes

delta = world_mini_crash - asian_crisis
type(delta)
datetime.timedelta
Intermediate Python for Finance

Creating relative datetimes

from datetime import timedelta
offset = timedelta(weeks = 1)
offset
datetime.timedelta(7)
dt - offset
datetime.datetime(2019, 1, 7, 0, 0)
Intermediate Python for Finance

Creating relative datetimes

offset = timedelta(days=16)
dt - offset
datetime.datetime(2018, 12, 29, 0, 0)
cur_week = last_week + timedelta(weeks=1)
# Do some work with date
# set last week variable to cur week and repeat
last_week = cur_week
source_dt = event_dt - timedelta(weeks=4)
# Use source datetime to look up market factors
Intermediate Python for Finance

Let's practice!

Intermediate Python for Finance

Preparing Video For Download...