Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Pandas Column to DateTime

I have one field in a pandas DataFrame that was imported as string format. It should be a datetime variable. How do I convert it to a datetime column and then filter based on date.

Example:

  • DataFrame Name: raw_data
  • Column Name: Mycol
  • Value Format in Column: '05SEP2014:00:00:00.000'
like image 591
Chris Avatar asked Nov 05 '14 17:11

Chris


People also ask

How do I convert columns to datetime?

If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime. You can try it with other formats then '%Y-%m-%d' but at least this works.

How do I convert a column to a time in Python?

Use pandas to_datetime() function to convert the column to DateTime on DataFrame. Use the format parameter of this method to specify the pattern of the DateTime string you wanted to convert.


2 Answers

Use the to_datetime function, specifying a format to match your data.

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f') 
like image 200
chrisb Avatar answered Oct 06 '22 11:10

chrisb


If you have more than one column to be converted you can do the following:

df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime) 
like image 22
Vlad Bezden Avatar answered Oct 06 '22 12:10

Vlad Bezden