The table is the login log of a hypothetical APP user. The goal is to count the highest continuous login time (number of days).
data = pd.read_excel('./time.xlsx',enconding='gb18030')
![Insert image description here](https://img-blog.csdnimg.cn/fd06b801fc694f1e8d52df22fbe9fdbd.png)
Merge tables, output unique times, and perform positive time sorting
df1 = data[['id','s_time']].rename(columns={
's_time': 'time'})
df2 = data[['id','e_time']].rename(columns={
'e_time': 'time'})
data_1 = pd.concat([df1,df2]).sort_values(by='time',ascending=True)
data_1
![Insert image description here](https://img-blog.csdnimg.cn/74809e2e88a64ade9ab6d8fcbdf3319f.png)
Output a unique time list, and a continuous time list (time_list)
def time_interval(li):
list_e,start_time = [],None
for x,y in zip(li,li[1:]):
if start_time is None:
start_time = x
if x==li[-1]:
list_e.append((start_time,y))
print(start_time,y)
start_time = None
if (y - x)/ np.timedelta64(1, 'D')> 1:
list_e.append((start_time,x))
start_time = None
else:
list_e.append((start_time,y))
return list_e
df_unique = data_1.groupby(['id'])['time'].agg({
'unique'})
df_unique['time_list'] = df_unique['unique'].apply(lambda x:time_interval(x))
df_unique
![Insert image description here](https://img-blog.csdnimg.cn/f5e1713028b5435ea3e93e96f038a527.png)
Perform time processing on time_list, output the number of consecutive login days within the time period, and then output the maximum number of days.
def days_time(x):
time_intervals = [(end - start)/ np.timedelta64(1, 'D') for start, end in x]
return time_interv
df_unique['days'] = df_unique['time_list'].apply(lambda x:days_time(x))
df_unique['max_day'] = df_unique['days'].apply(lambda x:max(x))
df_unique
![Insert image description here](https://img-blog.csdnimg.cn/68cd291c42614186bbec182a8ea39461.png)