Representing time with datetimes

Python intermedio per la finanza

Kennedy Behrman

Data Engineer, Author, Founder

Datetimes

Chart of rising stock price

Python intermedio per la finanza

Datetimes

Chart of Cuban trade deficit

Python intermedio per la finanza

Datetimes

from datetime import datetime
black_monday = datetime(1987, 10, 19)
print(black_monday)
datetime.datetime(1987, 10, 19, 0, 0)
Python intermedio per la finanza

Datetime now

datetime.now()
datetime.datetime(2019, 11, 6, 3, 48, 30, 886713)
Python intermedio per la finanza

Datetime from string

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)
Python intermedio per la finanza

Datetime from string

Year

  • %y Without century (01, 02, ..., 98, 99)
  • %Y With century (0001, 0002, ..., 1998, 1999, ..., 9999)

Month

  • %b Abbreviated names (Jan, Feb, ..., Nov, Dec)
  • %B Full names (January, February, ... November, December)
  • %m As numbers (01, 02, ..., 11, 12)

Day of Month

  • %d (01, 02, ..., 30, 31)
Python intermedio per la finanza

Datetime from string

Weekday

  • %a Abbreviated name (Sun, ... Sat)
  • %A Full name (Sunday, ... Saturday)
  • %w Number (0, ..., 6)

Hour

  • %H 24 hour (00, 01, ... 23)
  • %I 12 hour (01, 02, ... 12)
  • %M (01, 02, ..., 59)
Python intermedio per la finanza

Datetime from string

Seconds

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

Micro-seconds

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

AM/PM

  • %p (AM, PM)
Python intermedio per la finanza

Datetime from string

%m Months

%M Minutes

Python intermedio per la finanza

Datetime from string

"1837-05-10"

%Y

%m

%d

"%Y-%m-%d"
Python intermedio per la finanza

Datetime from string

"Friday, 17 May 01"

%A

%d

%B

%y

"%A, %d %B %y"
Python intermedio per la finanza

String from datetime

dt.strftime(format_string)
Python intermedio per la finanza

String from datetime

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'
Python intermedio per la finanza

Let's practice!

Python intermedio per la finanza

Preparing Video For Download...