時(shí)間索引
df.index = pd.DatetimeIndex(df.index)
時(shí)間只保留日期
df['date'] = df['time'].dt.date
將指定字段格式化為時(shí)間類型
df["date"] = pd.to_datetime(df['時(shí)間'])
轉(zhuǎn)化為北京時(shí)間
df['time'] = df['time'].dt.tz_convert('Asia/Shanghai')
轉(zhuǎn)為指定格式,可能會(huì)失去秒以后的精度
df['time'] = df['time'].dt.strftime("%Y-%m-%d %H:%M:%S")
dc.index = pd.to_datetime(dc.index, format='%Y%m%d', errors='ignore')
時(shí)間硼身,參與運(yùn)算
pd.DateOffset(days=2)
當(dāng)前時(shí)間
pd.Timestamp.now()
pd.to_datetime('today')
判斷時(shí)間是否當(dāng)天
pd.datetime.today().year == df.start_work.dt.year
df.time.astype('datetime64[ns]').dt.date == pd.to_datetime('today')
定義個(gè)天數(shù)
import datetime
days = lambda x: datetime.timedelta(days=x)
days(2)
同上,直接用 pd 包裝的
pd.Timedelta(days=2)
unix 時(shí)間戳
pd.to_datetime(ted.film_date, unit='ms')
按月(YMDHminS)采集合計(jì)數(shù)據(jù)
df.set_index('date').resample('M')['quantity'].sum()
df.set_index('date').groupby('name')['ext price'].resample("M").sum()
按天匯總,index 是 datetime 時(shí)間類型
df.groupby(by=df.index.date).agg({'uu':'count'})
按周匯總
df.groupby(by=df.index.weekday).uu.count()
按月進(jìn)行匯總
df.groupby(['name', pd.Grouper(key='date', freq='M')])['ext price'].sum()
按月進(jìn)行匯總
df.groupby(pd.Grouper(key='day', freq='1M')).sum()
按照年度甩栈,且截止到12月最后一天統(tǒng)計(jì) ext price 的 sum 值
df.groupby(['name', pd.Grouper(key='date', freq='A-DEC')])['ext price'].sum()
按月的平均重新采樣
df['Close'].resample('M').mean()
取時(shí)間范圍,并取工作日
rng = pd.date_range(start="6/1/2016",end="6/30/2016",freq='B')
重新定時(shí)數(shù)據(jù)頻度糕再,按一定補(bǔ)充方法
df.asfreq('D', method='pad')
# 時(shí)區(qū)量没,df.tz_convert('Europe/Berlin')
df.time.tz_localize(tz='Asia/Shanghai')
轉(zhuǎn)北京時(shí)間
df['Time'] = df['Time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Shanghai')
查看所有時(shí)區(qū)
from pytz import all_timezones
print (all_timezones)
時(shí)長,多久突想,兩個(gè)時(shí)間間隔時(shí)間殴蹄,時(shí)差
df['duration'] = pd.to_datetime(df['end']) - pd.to_datetime(df['begin'])
指定時(shí)間進(jìn)行對(duì)比
df.Time.astype('datetime64[ns]') < pd.to_datetime('2019-12-11 20:00:00', format='%Y-%m-%d %H:%M:%S')