日時の操作

Intermediate Python for Finance

Kennedy Behrman

Data Engineer, Author, Founder

Datetime の属性

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

日時の比較

等しい ==

より小さい <

より大きい >

Intermediate Python for Finance

日時の比較

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

日時の比較

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

日時の差分

  • <>== で比較
  • 減算は timedelta を返す
  • timedelta の属性: weeks, days, minutes, seconds, microseconds
Intermediate Python for Finance

日時の差分

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

相対的な日時の作成

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

相対的な日時の作成

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

相対的な日時の作成

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

相対的な日時の作成

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

練習しましょう!

Intermediate Python for Finance

Preparing Video For Download...