How to convert string to datetime format in pandas python?

I have an I_DATE column of type row (object) in a data frame named train, as shown below.

I_DATE 28-03-2012 2:15:00 PM 28-03-2012 2:17:28 PM 28-03-2012 2:50:50 PM 

How to convert I_DATE from string to datatime format and specify input string format. I saw some answers to this, but this is not for AM / PM format.

Also, how do I filter strings by date range in pandas?

+14
python pandas datetime
source share
2 answers

Use to_datetime , there is no need for format strings for which the parser / male is enough to handle it:

 In [51]: pd.to_datetime(df['I_DATE']) Out[51]: 0 2012-03-28 14:15:00 1 2012-03-28 14:17:28 2 2012-03-28 14:50:50 Name: I_DATE, dtype: datetime64[ns] 

To access the date / day / time component, use dt :

 In [54]: df['I_DATE'].dt.date Out[54]: 0 2012-03-28 1 2012-03-28 2 2012-03-28 dtype: object In [56]: df['I_DATE'].dt.time Out[56]: 0 14:15:00 1 14:17:28 2 14:50:50 dtype: object 

You can use strings for filtering as an example:

 In [59]: df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())}) df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')] Out[59]: date 35 2015-02-05 36 2015-02-06 37 2015-02-07 38 2015-02-08 39 2015-02-09 
+27
source share

although you can write code in several ways ... it was really easy to work on.

0
source share

All Articles