【发布时间】:2021-04-04 23:02:25
【问题描述】:
我有两个具有两种不同格式的 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'
【问题讨论】:
-
请在您的问题中包含两种数据格式的示例输入数据。
标签: python pandas dataframe datetime valueerror