我正在寻找一种方法来添加自定义日期到pd.to_datetime。例如:
csv_file = str(datetime.now().strftime('%Y-%m-%d')) + '.csv'
csv_file2 = str((datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')) + '.csv'
data = pd.concat(map(pd.read_csv, [csv_file, csv_file2]))
data['time'] = pd.to_datetime(data['time'], errors='coerce')
打印:
4 2021-08-23 00:00:40
20 2021-08-23 00:02:54
36 2021-08-23 00:05:09
...
pd。To_datetime不断添加今天的日期,这在csv_file的情况下是好的,但csv_file2需要包含明天的日期。
以下是csv文件的示例:
piece,time
2259,12:03:50
2259,12:07:42
2259,12:34:05
2259,12:45:29
的想法是创建辅助列file
,以区分tomorrow
和最后添加1 day
的条件,以比较new
列:
data = pd.concat(map(pd.read_csv, [csv_file, csv_file2]), keys=('today','tomorrow'))
data = data.reset_index(level=1, drop=True).rename_axis('new').reset_index()
d = pd.to_datetime(data['time'], errors='coerce')
data['time'] = np.where(data['new'].eq('tomorrow'), d + pd.Timedelta(1, 'd'), d)
或:
files = [csv_file, csv_file2]
names = ('today','tomorrow')
data= pd.concat([pd.read_csv(f).assign(new=name) for f, name in zip(files, names)])
d = pd.to_datetime(data['time'], errors='coerce')
data['time'] = np.where(data['new'].eq('tomorrow'), d + pd.Timedelta(1, 'd'), d)