In [ ]:
import numpy as np
import pandas as pd
from datetime import datetime
from datetime import timedelta

Basic


In [ ]:
now = datetime.now()
# now
now.year, now.month, now.day

In [ ]:
diff_dt = datetime(2018, 8, 31) - datetime(2018, 8, 30, 23, 0)
diff_dt.days, diff_dt.seconds, type(diff_dt), now + timedelta(1)

fromat, convert


In [ ]:
str(now), now.strftime('%Y-%m-%d %H:%M:%S')

In [ ]:
value = '2018-08-30 18:28:47'
dt1 = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
values = ['2018/08/30', '2018/08/31']
dt2 = [datetime.strptime(x, '%Y/%m/%d') for x in values] 
dt1, dt2

index, split


In [ ]:
dates = [datetime(2018, 9, x) for x in range(1, 7)]
ts = pd.Series(data = np.random.randn(6), index=dates)
dates, ts, type(ts.index), type(ts)

In [ ]:
# [start:end:step]
ts.index[0], ts[::2], ts['2018-9-2':'2018-9-5']

In [ ]:
ts['2018-9-3':'2018-9-5']

In [ ]:
ts.truncate(before='2018-09-03', after='2018-09-5')

range


In [ ]:
dt3 = pd.date_range(start='15/6/2016', periods=1000, freq='W-WED')
type(dt3)

In [ ]:
df3 = pd.DataFrame(data = np.random.randn(1000, 4), index=dt3, columns=['col' + str(x) for x in range(1, 5)])
df3[:5], df3.tail(5), df3.index.size, df3.columns.size, df3.size
df3.loc['2022-09'] # df3.loc['9-2022']

duplicate indices


In [ ]:
dt4 = pd.DatetimeIndex(data=['1/9/2018', '2/9/2018', '2/9/2018', '2/9/2018', '3/9/2018'])
df4 = pd.Series(data=np.arange(5), index=dt4)
dt4.is_unique, df4.index.is_unique

In [ ]:
df4['1/9/2018'], df4['2/9/2018'], df4['3/9/2018']

In [ ]:
df4

In [ ]:
df4_grouped = df4.groupby(level=0) # index only one level
df4_grouped.count()

In [ ]:
ts2 = ts[::2]
ts2

In [ ]:
ts3 = ts2.resample('D')
ts3.mean()

In [ ]:
dt5 = pd.date_range('1/9/2018', periods=12, freq='T')
s5 = pd.Series(data=np.arange(12), index=dt5)
s5

In [ ]:
s5_1 = s5.resample(rule='5min')
s5_1.mean()