Práce s datetimes

Intermediate Python for Finance

Kennedy Behrman

Data Engineer, Author, Founder

Atributy datetime

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

Porovnávání datetimes

rovná se ==

menší než <

větší než >

Intermediate Python for Finance

Porovnávání 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

Porovnávání 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

Rozdíl mezi datetimes

  • Porovnání pomocí <, > nebo ==.
  • Odčítání vrátí objekt timedelta.
  • Atributy timedelta: weeks, days, minutes, seconds, microseconds
Intermediate Python for Finance

Rozdíl mezi datetimes

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

Vytváření relativních 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

Vytváření relativních datetimes

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

Vytváření relativních 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

Vytváření relativních 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

Lass uns üben!

Intermediate Python for Finance

Preparing Video For Download...