time模块
time.time() 返回当前时间戳
time.localtime 将一个时间戳转换为当前时区的struct_time,即格式化时间。
time.mktime():将一个struct_time转化为时间戳
time.strftime( ) 把一个代表时间的元组或者struct_time转化为格式化的时间字符串,格式由参数format决定。
%y:两位年份 %Y:四位年份 %m:月份 %d:天 %H:时 %I:时 %M:分
%S:秒
%a:星期简写【Mon—>Monday】
%A:星期全称【Monday】
%b:月份简称【Jun—>June】
%B:月份简称【June】
%c:本地适当的日期和时间代表
%p:本地等价与AM或者PM
print(time.strftime("%Y-%m",local))
datetime模块
datetime有date, time, datetime, timedelta类型
dd = date(2018,3,11)
print(dd,type(dd))
print(dd.month)
2018-03-11 <class 'datetime.date'>
3
pandas里的时间函数
print(pd.Timestamp(2012,6,1))
print(pd.Timestamp("20120501"))
print(pd.Timestamp("2012/5/1"))
2012-06-01 00:00:00
2012-05-01 00:00:00
2012-05-01 00:00:00
提取pandas里的年月信息
print(hushen["交易日期"].dtype)
hushen["交易日期"] = pd.to_datetime(hushen["交易日期"],format ="%Y-%m-%d")
print(hushen["交易日期"].dtype)
hushen['year'] = pd.DatetimeIndex(hushen["交易日期"]).year
print(hushen)
object
datetime64[ns]
指数代码 交易日期 收盘指数 18均线 year
0 300 2015-01-28 3525.323 3552.751333 2015
1 300 2015-01-29 3481.798 3543.876722 2015
2 300 2015-01-30 3434.390 3532.395111 2015
pandas里原始的日期类型为object,处理时首先要将其转变为datetime类型,使用pd.to_datetime函数,若格式不严格统一,添加errors='ignore’参数。
生成等差的时间
freq参数表示频率,Q为季度,2m表示两个月
x = pd.period_range('2019-01',periods=13,freq='Q')
print(x,type(x))
x = pd.period_range("2019-01", periods=13, freq="2m")
print(x)
PeriodIndex(['2019Q1', '2019Q2', '2019Q3', '2019Q4', '2020Q1', '2020Q2',
'2020Q3', '2020Q4', '2021Q1', '2021Q2', '2021Q3', '2021Q4',
'2022Q1'],
dtype='period[Q-DEC]', freq='Q-DEC') <class 'pandas.core.indexes.period.PeriodIndex'>
PeriodIndex(['2019-01', '2019-03', '2019-05', '2019-07', '2019-09', '2019-11',
'2020-01', '2020-03', '2020-05', '2020-07', '2020-09', '2020-11',
'2021-01'],
dtype='period[2M]', freq='2M')