python数据框转换多种日期时间格式 [英] python dataframe converting multiple datetime formats

查看:84
本文介绍了python数据框转换多种日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的pandas.dataframe("col"列有两种格式):

I have a pandas.dataframe like this ('col' column has two formats):

    col                            val
'12/1/2013'                       value1
'1/22/2014 12:00:01 AM'           value2
'12/10/2013'                      value3
'12/31/2013'                      value4 

我想将它们转换为日期时间,并且正在考虑使用:

I want to convert them into datetime, and I am considering using:

test_df['col']= test_df['col'].map(lambda x: datetime.strptime(x, '%m/%d/%Y'))    
test_df['col']= test_df['col'].map(lambda x: datetime.strptime(x, '%m/%d/%Y %H:%M %p'))

显然,它们中的任何一个都可以为整个df工作.我正在考虑使用try and,但没有任何运气,没有任何建议吗?

Obviously either of them works for the whole df. I'm thinking about using try and except but didn't get any luck, any suggestions?

推荐答案

只需使用

Just use to_datetime, it's man/woman enough to handle both those formats:

In [4]:
df['col'] = pd.to_datetime(df['col'])
df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 4 entries, 0 to 3
Data columns (total 2 columns):
col    4 non-null datetime64[ns]
val    4 non-null object
dtypes: datetime64[ns](1), object(1)
memory usage: 96.0+ bytes

df现在看起来像这样:

The df now looks likes this:

In [5]:
df

Out[5]:
                  col     val
0 2013-12-01 00:00:00  value1
1 2014-01-22 00:00:01  value2
2 2013-12-10 00:00:00  value3
3 2013-12-31 00:00:00  value4

这篇关于python数据框转换多种日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆