将日期添加到pd.to_datetime

2024-04-26 05:31:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种将自定义日期添加到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_文件可以,但是csv_文件2需要包含明天的日期

以下是csv文件的示例:

piece,time
2259,12:03:50
2259,12:07:42
2259,12:34:05
2259,12:45:29

1条回答
网友
1楼 · 发布于 2024-04-26 05:31:30

想法是创建辅助列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)

相关问题 更多 >