目标:object类型的时间戳转datetime类型再转int类型时间戳进行diff计算时间差
- 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
- 处理数据
对于“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("'", ''))
- 再逐列转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 '')
- 转回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))



