日時で時間を表す

Intermediate Python for Finance

Kennedy Behrman

Data Engineer, Author, Founder

日時型

株価上昇のチャート

Intermediate Python for Finance

日時型

キューバの貿易赤字のチャート

Intermediate Python for Finance

日時型

from datetime import datetime
black_monday = datetime(1987, 10, 19)
print(black_monday)
datetime.datetime(1987, 10, 19, 0, 0)
Intermediate Python for Finance

現在の日時

datetime.now()
datetime.datetime(2019, 11, 6, 3, 48, 30, 886713)
Intermediate Python for Finance

文字列から日時

black_monday_str = "Monday, October 19, 1987. 9:30 am"
format_str = "%A, %B %d, %Y. %I:%M %p"
datetime.datetime.strptime(black_monday_str, format_str)
datetime.datetime(1987, 10, 19, 9, 30)
Intermediate Python for Finance

文字列から日時

  • %y 西暦下2桁 (01, 02, ..., 98, 99)
  • %Y 西暦4桁 (0001, 0002, ..., 1998, 1999, ..., 9999)

  • %b 省略名 (Jan, Feb, ..., Nov, Dec)
  • %B 英語名 (January, February, ... November, December)
  • %m 数値 (01, 02, ..., 11, 12)

  • %d (01, 02, ..., 30, 31)
Intermediate Python for Finance

文字列から日時

曜日

  • %a 省略名 (Sun, ... Sat)
  • %A 英語名 (Sunday, ... Saturday)
  • %w 数値 (0, ..., 6)

  • %H 24時間制 (00, 01, ... 23)
  • %I 12時間制 (01, 02, ... 12)
  • %M (01, 02, ..., 59)
Intermediate Python for Finance

文字列から日時

  • %S (00, 01, ... 59)

マイクロ秒

  • %f (000000, 000001, ... 999999)

AM/PM

  • %p (AM, PM)
Intermediate Python for Finance

文字列から日時

%m

%M

Intermediate Python for Finance

文字列から日時

"1837-05-10"

%Y

%m

%d

"%Y-%m-%d"
Intermediate Python for Finance

文字列から日時

"Friday, 17 May 01"

%A

%d

%B

%y

"%A, %d %B %y"
Intermediate Python for Finance

日時から文字列

dt.strftime(format_string)
Intermediate Python for Finance

日時から文字列

great_depression_crash = datetime.datetime(1929, 10, 29)
great_depression_crash
datetime.datetime(1929, 10, 29, 0, 0)
great_depression_crash.strftime("%a, %b %d, %Y")
'Tue, Oct 29, 1929'
Intermediate Python for Finance

演習しましょう!

Intermediate Python for Finance

Preparing Video For Download...