Python数据分析DAY4

目录

time模块

入门案例 

datetime模块

date类

datetime类

timedelta类

pandas时间序列类型

时间戳

 时间间隔--实现datetime加减

时间转换

生成时间戳范围

 时间频率转换

shift()时间频率进行位移

 Pandas时期:Period()

重采样resample


time模块

        在py中有三种格式:timestamp时间戳、struct_times时间元组、format time格式化时间

  • 入门案例 

import time
#生产timestamp
t=time.time()
print(t)
#将timesstamp转换为struct_time
t1=time.localtime();
print(t1)
print("-----------------")
print(t1.tm_year,t1.tm_mon,t1.tm_mday)
#将timesstamp转换成struct_time
print(time.localtime(t))
#吧struct_time 准成时间更是
print(time.strftime('%Y-%m-%d',t1))
#对于对时间的加减,比如多一天或少一天,可以先转成时间戳使用秒相加后再转成时间格式
my_str='2023-9-25 19:19:19'
st=time.strptime(my_str,'%Y-%m-%d %X')
t123=time.mktime(st)
print(t123)
t123=t123+24*60*60*10
print(t123)
newt=time.localtime(t123)
print(time.strftime('%Y-%m-%d',newt))

datetime模块

        datatime模块重新封装了time模块,提供更多接口,提供的类有: date,time,datetime,

timedelta,tzinfo。

  • date类

        datetime.date(year,month,day)

#返回一个表示当地本地日期的date对象;
print(date.today())
#根据给定的时间戳,返回一个date对象
print(date.fromtimestamp(time.time()))

        date方法和属性

名称描述
year/month/day返回年/月/日
replace(year,month,day)生成一个新的date对象,并用参数中的数值代替原先。
timetuple()返回日期对应的time.struct time对象
weekday()返回星期几,如果是星期一返回0
isoweekday()返回星期几,如果是星期一返回1
isoformat返回格式如"YYYY-MM-DD'的字符串
strftime(fmt)利和time模块format相同
  • datetime类

print(datetime.now())
print(datetime.today())
#将datetime转化为指定格式的字符串
print(datetime.now().strftime("%Y-%m-%d %X"))

  • timedelta类

         使用timedelta可以很方便的在日期上做天days,小时hour,分钟,秒,毫秒,微妙的时间计算,如果要计算月份则需要另外的办法。

dt1=dt+timedelta(days=-1)
print(dt1)

pandas时间序列类型

  • 时间戳

        datetime的代替品,时间戳相当于python的datetime大多数情况下可以互换。

#不能将错误日期转换为Timestamp
print(pd.Timestamp('2022-01-01'))
#unit参数为s:这将转换以秒为单位表示Unix历元的浮点值
print(pd.Timestamp(time.time(), unit="s"))
print(pd.Timestamp(time.time()))
#可以单独设置年月日最小到day
print(pd.Timestamp(2023,9,25,12))
  •  时间间隔--实现datetime加减

        表示持续时间,即两个日期或时间之间的差异。

ts=pd.Timestamp('2023-09-25 12')
print(ts)
#减一天
print(ts+pd.Timedelta(-1,'D'))
#时间间隔
td=pd.Timedelta(days=5,minutes=50,seconds=20)
print(td)
print(ts+td)
#获取总秒数 可以用于和time.time相加
print(td.total_seconds())
#当前时间往后100天的日期
now=datetime.now();
print(now)
d1=now+pd.Timedelta(days=100)
print(d1)
print(d1.strftime('%Y-%m-%d'))
  • 时间转换

        to_datetime转换时间戳(将文本,字符转换成时间戳)

df=pd.DataFrame({'year':[2015,2016],'month':[2,3],'day':[4,5]})
print(df)
print(pd.to_datetime(df))
#将字符串转datetime
d1=pd.to_datetime(['11-12-2021'])
print(d1)
print(pd.to_datetime(["2023/11/11"]))
#除了可以将文本数据转为时间戳外,还可以将unix时间转为时间戳
d2=pd.to_datetime([1349720105,1349806505],unit="s")
print(d2)
#自动识别异常
print(pd.to_datetime('210605'))
print(pd.to_datetime('210605',yearfirst=True))
#配合unit参数,使用非unix时间
#prigin参考起始 单位可以是h m s
print(pd.to_datetime([1,2,3],unit='D',origin=pd.Timestamp('2023-11-11')))
#不可转换日期/时间
#如果日期不符合时间戳限制,则传递errors='ignore'返回原始输入,errors='coerce 转换成NaT
print(pd.to_datetime(['120211204'],errors='ignore'))
print(pd.to_datetime(['120211204'],errors='coerce'))
  • 生成时间戳范围

        生成例如"2023-9-27"包括在内的之后八天的时间戳,我们可以使用date_range和bdate_range(只有工作日没有双休的日期)完成时间戳范围的生成。

        date_range()返回固定频率的DatetimeIndex

#默认是包含开始和结束时间,默认频率使用时间D
dr=pd.date_range(start='9/27/2023',end='12/31/2023')
#print(dr)
#指定开始日期,设置日期间隔数
print(pd.date_range(start='1/1/2024',periods=9))

#从指定星期几开始算起,每周  一下是每周一的例子
print(pd.date_range('2022/1/1','2022/2/1',freq='W-MON'))
#如果想要在开始和结尾日前选择开区间或者闭区间可以添加closed标签
print(pd.date_range(start='2023/9/9',end='2023/9/19',closed='right'))
  •  时间频率转换

  • shift()时间频率进行位移

df=pd.DataFrame(np.random.rand(16).reshape((4,4)),index=pd.date_range('20210101','20210104'),columns=list('ABCD'))
print(df)
#数值后移,模式为行
c=df.shift(periods=2)
#数值后移,设置为列
a=df.shift(periods=1,axis="columns")
#数值后移,NAN填充0
b=df.shift(periods=3,fill_value=0)
#数值后移,对时间索引移动
d=df.shift(periods=3,freq='D')
print('------------后移---------------')
print(d)


e=df.shift(1)
print('------------昨天/今日比较---------------')
#计算变化百分比,这里是与上一天对比
print(df/e-1)
  •  Pandas时期:Period()

#Period可以直接相加减
print(p+1)
#period_range函数可用于创建规则的时期范围
rng=pd.period_range('2023-9-10','2023-9-20')
print(rng)
print(pd.Series(np.random.rand(11),index=rng))

#PeriodIndex类的构造函数允许直接使用一组字符串表示一段时期
values=['200103','200104','200105']
index=pd.PeriodIndex(values,freq='M')
print(index)

#时期的频率转换asfreq
p=pd.Period('2021',freq='A-DEC')
print(p)
print(p.asfreq('M'))
  • 重采样resample

rng=pd.date_range('20170101',periods=12)
ts=pd.Series(np.arange(1,13),index=rng)
print(ts)

print('-------------------------')
print(ts.resample('5D').sum())

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值