栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pandas进行时间处理

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pandas进行时间处理

时间处理

目标:object类型的时间戳转datetime类型再转int类型时间戳进行diff计算时间差

  1. object类型的时间戳转datetime(不加8小时会出现报错)
data.loc[:,'time'] = pd.to_datetime(data.loc[:,'time'], unit='s')
data['time']=data['time'].apply(lambda x:x+ datetime.timedelta(hours=8))
data['etl_day'] = data['collecttime'].apply(lambda x: x.strftime('%Y-%m-%d'))

datetime.strftime('%' )这个的前提是数据类型为datetime

  1. 处理数据

对于“ss [“20211110”,“20211112”,“20211126”]”并且每一行长度不同的时间列处理方法(列名为A):

先转成字符串table['A']= table['A'].apply(lambda x:str(x))

再切分table=table[0].str.split(' ',expand = True),将ss 和对应时间列分开

空值补字符串0,否则后面不好用replace处理。

table.fillna(str(0),inplace=True)

按自己需要的格式处理

table = table.applymap(lambda x: x.replace('[', ''))
table = table.applymap(lambda x: x.replace(']', ''))
table = table.applymap(lambda x: x.replace(',', ''))
table = table.applymap(lambda x: x.replace("'", ''))
  1. 再逐列转datetime,把Nat换成‘ ’,否则转回时间戳会报错
for i in table.columns:
	
table[i] =  pd.to_datetime(table[i],errors='coerce')
table[i] = table[i].apply(lambda x: x.strftime('%Y-%m-%d')if not pd.isnull(x) else '')
  1. 转回int类型时间戳
 def change(x):
        if x != '':
            x = datetime.datetime.strptime(x, "%Y-%m-%d")
            return int(time.mktime(x.timetuple())) 
        else:
            return int(0)
for i in test.columns:
    test[i]= test[i].apply(lambda x:change(x))
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/917895.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号