I’m looking for a way to add custom date to pd.to_datetime. So, for example:
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')
Print:
4 2021-08-23 00:00:40 20 2021-08-23 00:02:54 36 2021-08-23 00:05:09 ...
pd.to_datetime keeps adding today’s date which is fine in case of csv_file but csv_file2 need to contain tomorrow’s date.
Here’s sample of csv files:
piece,time 2259,12:03:50 2259,12:07:42 2259,12:34:05 2259,12:45:29
Advertisement
Answer
Idea is create helper column file
for distingush if tomorrow
and last add 1 day
by condition for compare new
column:
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)
Or:
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)