Convert Pandas Column to DateTime

I have one field in a pandas DataFrame that has been imported as a string format. It must be a datetime variable. How to convert it to datetime column and then filter by date.

Example:

  • DataFrame Name: raw_data strong>
  • Column Name: Mycol
  • Column format value: '05SEP2014: 00: 00: 00.000'
+171
python pandas datetime
Nov 05 '14 at 17:24
source share
4 answers

Use the to_datetime function to to_datetime format that matches your data.

 raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f') 
+316
Nov 05 '14 at 17:50
source share

You can use the DataFrame .apply() method to work with values ​​in Mycol:

 >>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol']) >>> df Mycol 0 05SEP2014:00:00:00.000 >>> import datetime as dt >>> df['Mycol'] = df['Mycol'].apply(lambda x: dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f')) >>> df Mycol 0 2014-09-05 
+42
Nov 05 '14 at 17:51
source share
 raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f') 

works, however, this leads to a Python warning about the value trying to be set on the copy slice from the DataFrame. Use .loc[row_indexer,col_indexer] = value

I would suggest that this is due to some indexing of the chains.

+11
Mar 13 '17 at 20:46 on
source share
 import pandas as pd df["MyCol"]=pd.to_datetime(df["MyCol"]) 
0
Dec 02 '18 at 3:55
source share



All Articles