繁体   English   中英

使用 raise ValueError python 允许两种日期时间格式

[英]Allow two datetime format using raise ValueError python

我有两个 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=重定向到 function ,它将克服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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM