Python Basics – Datetime

Datetimes – basic

Datetime

from datetime import datetime
black_monday = datetim(1987, 10, 19)
> datetime.datetime(1987, 10, 19, 0, 0)

Current Datetime

from datetime import datetime
datetime.now()

Datetime from a 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)
Year: %y ... 01-99
      %Y ... 0000-9999
Month : %b ... Jan-Dec
        %B ... January-December
        %m ... 01-12
Day : %d ... 01-31
Weekday : %a ... Sun-Sat
          %A ... Sunday-Saturday
          %w ... 0-6
Hour : %H ... 00-23
       %I ... 00-12 
Seconds : %S ... 00-59
Microseconds : %f ... 000000-999999
AM/PM : %p
"1937-05-10" --> "%Y-%m-%d"
"Friday, 19 May 01" --> "%A, %d %B %y"

String from Datetime

great_depression = datetime.datetime(1929, 10, 29)
great_depression.strftime("%a, %b %d, %Y")
> "Tue, Oct 29, 1929"

 

Datetimes – working with

Datetime attributes

# March 10, 2000 Tech Bubble Crash
tech_bubble = datetime(2000, 3, 10)
# year
yr  = tech_bubble.year
# month
mth = tech_bubble.month
# day
day = tech_bubble.day
print(f"Year: {yr}, Month: {mth}, Day: {day}")

> Year: 2000, Month: 3, Day: 10

Comparing datetime

from datetime import datetime
lehman = datetime.datetime(2008, 9, 15, 0, 0)
morgan_stanley = datetime.datetime(2008, 9, 22, 0, 0)
tarp = datetime.datetime(2008, 10, 3, 0, 0)

# Lehman Brothers before Morgan Stanley?
lehman_first = lehman < morgan_stanley
print(f"It is {lehman_first} that Lehman Brothers declared bankruptcy first.") 
> It is True that Lehman Brothers declared bankruptcy first.

# Goldman Sachs after TARP?
tarp_first = goldman_sachs > tarp
print(f"It is {tarp_first} that TARP was approved first.")
It is False that TARP was approved first.

# Goldman Sachs and Morgan Stanley same day?
same_time = goldman_sachs == morgan_stanley
print(f"It is {same_time} that Morgan Stanley and Goldman Sachs acted simultaneously")
It is True that Morgan Stanley and Goldman Sachs acted simultaneously

 

Datetime calculation

from datetime import datetime, timedelta
# TARP passed Oct 3 2008
tarp = datetime(2008, 10, 3)

# Seven days before TARP
week_before = tarp - timedelta(days = 7)
# Print week_before
print(week_before)
> 2008-09-26 00:00:00

# One week after TARP
week_after = tarp + timedelta(weeks = 1)
# Print week_after
print(week_after)
> 2008-10-10 00:00:00

# One year after TARP
year_after = tarp + timedelta(weeks = 52)
# Print year_after
print(year_after)
> 2009-10-02 00:00:00