我有两个csv文件,它们有两种不同的格式,即'%m/%d/%Y %H:%M:%S'
和'%d/%m/%Y %H:%M:%S'
。因此,我会得到这样的ValueError:
ValueError: time data '14/12/2020 17:43:15' does not match format '%m/%d/%Y %H:%M:%S'
来自file1.csv
的样本数据,其中月份位于中间:
timestamp
15/12/2020 11:01:54
15/12/2020 11:02:54
15/12/2020 13:33:24
而file2.csv
,月份在前:
timestamp
12/15/2020 11:01:54
12/15/2020 11:02:54
12/15/2020 13:33:24
该列以字符串形式出现,然后我需要进行转换以仅提取date
。这是代码:
responses_df['date_only'] = [datetime.strptime(val, format='%m/%d/%Y %H:%M:%S').date() for val in responses_df['timestamp']]
我的计划是将format=
重定向到一个将克服ValueError
的函数,并将格式从'%m/%d/%Y %H:%M:%S'
更改为'%d/%m/%Y %H:%M:%S'
。
像这样的…:
responses_df['date_only'] = [datetime.strptime(val, format=get_format()).date() for val in responses_df['timestamp']]
def get_format():
if ValueError is raised, use '%d/%m/%Y %H:%M:%S'
else, use '%m/%d/%Y %H:%M:%S'
尝试
s1 = pd.to_datetime(df['timestamp'],format='%m/%d/%Y %H:%M:%S', errors='coerce')
s2 = pd.to_datetime(df['timestamp'],format='%d/%m/%Y %H:%M:%S', errors='coerce')
然后
df['new']=s1.fillna(s2)
假设在连接到单个df
之前,两个文件作为两个不同的数据帧读入——对于第一个文件,传递dayfirst=True
。对于第二个文件,不要。然后,使用dt.strftime()
:将两者转换为所需格式
df1['timestamp'] = pd.to_datetime(df1['timestamp'], dayfirst=True).dt.strftime('%d/%m/%Y %H:%M:%S')
df2['timestamp'] = pd.to_datetime(df2['timestamp']).dt.strftime('%d/%m/%Y %H:%M:%S')
df1, df2
Out[1]:
( timestamp
0 15/12/2020 11:01:54
1 15/12/2020 11:02:54
2 15/12/2020 13:33:24,
timestamp
0 15/12/2020 11:01:54
1 15/12/2020 11:02:54
2 15/12/2020 13:33:24)