![](/img/trans.png)
[英]Unable to raise ValueError in python using if and else statements
[英]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.