时间序列TimeSries
rng = pd.date_range('1/1/2012', periods=100, freq='S')
ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
ts.resample('5Min').sum()
ts_utc = ts.tz_localize('UTC')
ts_utc = ts.tz_localize('US/Eastern')
ps = ts.to_period('Y')
ps = ts.to_period('M')
ps = ts.to_period('D')
ps = ts.to_period('Q')
ps = ts.to_period('D').strftime('%Y, %m, %d, %B, %r')
ts.to_period('D').loc[pd.to_datetime('2022-01-31/2022-02-06')]
df.asfreq(freq='D',fill_value=0)
df.asfreq(freq='D',method='ffill')
ts = ps.to_timestamp()
df['timestamp'].astype('datetime64')
df['timestamp'].astype('datetime64[ns]')
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y%m%d')
时间索引的特性
import numpy as np
dates=['20220101','20220102','20220103','20220104','20220105']
df = pd.DataFrame(np.random.randn(5), index=[pd.to_datetime(date) for date in dates])
df[::2]
df[::-2]
df + df[::2]
df.loc['20220101']
df.loc['2022-01-01']
df.loc['20220101': '20220103']
df.loc['2022-01-01': '2022-01-03']
df.loc['2022']
df.loc['2022-01']
df.index.year
df.index.month
df.index.day
df.index.weekofyear
df.index.weekday
df['A'].shift(2)
df.tshift(2, freq='D')
df.tshift(2, freq='M')
df.tshift(2, freq='Y')
import datetime
df.assign(date=lambda x: x['date'].astype('datetime64[ns]').apply(lambda x: x + datetime.timedelta(1)))
df.asfreq(freq='30S', fill_value=1.0)
df.asfreq(freq='30S', method='bfill')
python内置时间模块datetime
t = datetime.datetime(2022, 2, 5, 9, 30, 15, 0)
import datetime
now = datetime.datetime.now()
year= now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
microsecond = now.microsecond
import datetime
delta = datetime.timedelta(1,60,0)
tomorrow = now + delta
时间格式转换
代码 |
说明 |
%Y |
4位数的年 |
%y |
2位数的年 |
%m |
2位数的月[01,12] |
%d |
2位数的日[01,31] |
%H |
时(24小时制)[00,23] |
%l |
时(12小时制)[01,12] |
%M |
2位数的分[00,59] |
%S |
秒[00,61]有闰秒的存在 |
%w |
用整数表示的星期几[0(星期天),6] |
%F |
%Y-%m-%d简写形式例如,2017-06-27 |
%D |
%m/%d/%y简写形式 |
stamp = datetime(2022, 2, 5)
stamp.strftime('%Y-%m-%d')
strdate = '2022-02-05'
stamp = datetime.datetime.strptime(strdate, '%Y-%m-%d')