Often the time and date information won’t just be in a separate column, but instead be the actual datatime index, so let's learn how to deal with this sort of data with pandas!
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Note that from datetime import datetime
is differnt from import datetime
from datetime import datetime
To illustrate the order of arguments Note that hour in 24 hour format
# To illustrate the order of arguments
my_year = 2017
my_month = 1
my_day = 2
my_hour = 13
my_minute = 30
my_second = 15
Create a datetime object
-Use datetime()
method to create a datetime object, January 2nd, 2017
my_date = datetime(my_year,my_month,my_day)
Time Defaults to 0:00
my_date
You can specify hours, minutes, seconds in hh, mm, ss format January 2nd, 2017 at 13:30:15
my_date_time = datetime(my_year,my_month,my_day,my_hour,my_minute,my_second)
Alternatively,
my_date_time
The data type is datetime.datetime
type(my_date_time)
You can grab any part of the datetime object you want
my_date.day
my_date_time.hour
You'll usually deal with time series as an index when working with pandas dataframes obtained from some sort of financial API. Fortunately pandas has a lot of functions and methods to work with time series!
Use datetime()
method to create a datetime object
first_two = [datetime(2016, 1, 1), datetime(2016, 1, 2)]
first_two
To create an index, pass the list created to DatetimeIndex()
dt_ind = pd.DatetimeIndex(first_two)
dt_ind
Attached Some Random Data
data = np.random.randn(2,2)
print(data)
cols = ['A','B']
Use DataFrame()
to create a pandas DataFrame
df = pd.DataFrame(data,dt_ind,cols)
df
df.index
df.index.argmax()
df.index.max()
df.index.argmin()
df.index.min()