。。。。
import datetime
a = [10100,108,12.2,12.32,17,208,17,308,17,408,17,508,17,608,17,708,17,808,14.2,14.32,17,908,17,808,1708]
td = datetime.date.today()
y = td.year
m = td.month
d = td.day
hh = 0
mm = 0
ans = []
err = []
old = ''
for i in range(len(a)):
v = a[i]
if v // 10000 > 0:
m = v // 10000
v %= 10000
if v // 100 > 0:
d = v // 100
v %= 100
hh = ('0' + str(int(v)))[-2:]
mm = '00' if a[i] - int(a[i]) == 0 else (str(a[i]).split('.')[1] + '00')[:2]
tm = '{}-{}-{} {}:{}'.format(y,m,d,hh,mm)
time = datetime.datetime(y,m,d,int(hh),int(mm))
if not old or old < time:
while old and d - old.day > 1:
ans.append(['{}-{}-{} {}:{}'.format(y,m,old.day + 1,'00','00'),(d + 1)* 100,'补全'])
old = datetime.datetime(y,m,old.day + 1,0,0)
ans.append([tm,a[i]])
old = time
else:
err.append('第 {} 行数据异常:{},前一个有效数据为:{}'.format(i + 1,a[i],old))
#print('时间:{},转换成完整时间格式:{}'.format(a[i],tm))
for i in range(len(ans)):
print(ans[i])
for i in range(len(err)):
print(err[i])
参考GPT和自己的思路:以下是Python代码示例,使用pandas库来读取、操作和保存Excel文件,使用datetime库来处理时间格式:
import pandas as pd
from datetime import datetime, timedelta
# 读取Excel文件
df = pd.read_excel('filename.xlsx', parse_dates=[0], names=['B', 'C'], header=None)
# 生成需要补全的时间序列
start_date = datetime(2000, 1, 1)
end_date = datetime(2023, 12, 31)
time_range = pd.date_range(start=start_date, end=end_date, freq='D')
missing_dates = time_range.difference(df['B'])
# 在DataFrame中插入缺失的时间数据
for missing_date in missing_dates:
new_row = pd.DataFrame({'B': [missing_date], 'C': [0]})
df = pd.concat([df, new_row], ignore_index=True)
# 处理问题数据
for index, row in df.iterrows():
date = row['B']
if date.month == 2 and date.day == 29: # 处理闰年问题
date += timedelta(days=1)
df.at[index, 'B'] = date
if row['B'] == datetime(2006, 4, 16, 2, 0): # 跳过错误数据
continue
if row['B'] == datetime(2022, 4, 20, 14, 34): # 处理问题数据
new_date = datetime(2022, 4, 20)
df.at[index, 'B'] = new_date
new_row = pd.DataFrame({'B': [date], 'C': [0.5]})
df = pd.concat([df.iloc[:index], new_row, df.iloc[index:]], ignore_index=True)
# 保存到Excel文件
df.to_excel('filename_updated.xlsx', index=False)
代码中使用pd.read_excel()函数读取Excel文件,并通过parse_dates=[0]参数将第一列解析为日期格式。然后生成需要补全的时间序列,并使用difference()函数来找出缺失的时间数据。接着,遍历DataFrame中的每一行,处理闰年问题、跳过错误数据、处理时间数据前面的整时和插入缺失的数据。最后,使用to_excel()函数将更新后的数据保存到Excel文件中。
以下答案由GPT-3.5大模型与博主波罗歌共同编写:
针对您提出的问题,以下是实现Python对Excel文件时间格式补全的代码:
import pandas as pd
from datetime import datetime, timedelta
def fill_time_format(file_path):
# 读取Excel文件
df = pd.read_excel(file_path)
# 遍历每一行数据
for i, row in df.iterrows():
# 判断是否需要补全月份日期格式
if pd.isnull(row['日期']):
pre_date = df.loc[i-1, '日期']
next_date = df.loc[i+1, '日期']
if pd.notnull(pre_date) and pd.notnull(next_date):
pre_month = datetime.strptime(str(pre_date), '%Y%m').strftime('%m')
next_month = datetime.strptime(str(next_date), '%Y%m').strftime('%m')
if pre_month != next_month:
fill_month = int(pre_month)
while fill_month < int(next_month):
fill_date_str = str(df.loc[i-1, '日期'])[0:4] + str(fill_month).zfill(2) + '01'
df = df.append({'日期': int(fill_date_str), '收盘价': None},
ignore_index=True, sort=False)
fill_month += 1
# 插入60208、60408数据组
if pd.notnull(row['日期']):
if row['日期'] == 60208:
df = df.append({'日期': 60408, '收盘价': None},
ignore_index=True, sort=False)
elif row['日期'] == 60408:
df = df.append({'日期': 60208, '收盘价': None},
ignore_index=True, sort=False)
# 跳过错误数据并记录日志
if pd.isnull(row['收盘价']):
print('Error data: ', row['日期'], '-', row['开盘价'])
# 在时间前面插入整点时间
if pd.notnull(row['收盘价']) and row['日期'] // 100 % 100 == 4:
hour_date_str = str(row['日期'])[:-2] + '00'
df = df.append({'日期': int(hour_date_str), '收盘价': None},
ignore_index=True, sort=False)
# 保存修改后的Excel文件
df.to_excel(file_path, index=False)
if __name__ == '__main__':
fill_time_format('example.xlsx')
该代码的实现逻辑如下:
针对第一个问题,遍历Excel表格中的每一行数据,判断是否需要补全月份日期格式。如果某一行的日期为空,就根据前后两个数据的日期分别取月份,如果这两个月份不相等,则在这两个月份之间补全缺失日期的数据,并将它们插入到数据帧的空值列表中。
针对第二个问题,在遍历过程中查找到60208或60408,就在数据帧的末尾添加缺失的数据。
针对第三个问题,如果某一行数据的收盘价为空,就打印错误日志并跳过该数据行。如果日期的最后两位为04,则在该行数据前面插入整点时间。
最后,将修改后的数据帧保存为Excel文件,代码中的example.xlsx
为示例文件路径,可以根据需要进行修改。
如果我的回答解决了您的问题,请采纳!
能对B列进行说明不,整数部分的含义和小数部分的含义,以及除了数字从上到下为从小到大之外的,判定为无效的规则,看不太懂问题
不知道你这个问题是否已经解决, 如果还没有解决的话: