0

I have the following pandas DataFrame:

data = pd.DataFrame({"id": [1, 2, 3, 4, 5],
                     "end_time": ["2016-01-13", "2016-01-01", "2016-11-12", "2016-01-17", "2016-03-13"]})

I want to transform the end_time column to a column of datetime objects. But when I do it like this (like it is suggested everywhere):

data["end"] = data["end_time"].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d"))

the output is still a string column:

    id  end_time    end
0   1   2016-01-13  2016-01-13
1   2   2016-01-01  2016-01-01
2   3   2016-11-12  2016-11-12
3   4   2016-01-17  2016-01-17
4   5   2016-03-13  2016-03-13

How to solve this?

Peter
  • 722
  • 6
  • 24

1 Answers1

2

strftime is designed to return a string object, details. If we want to convert end_time to datetime64[ns] and assign to new column named end then we can use:

data['end'] = pd.to_datetime(data.end_time) 

strptime will also covert the string to datetime64[ns]. But preferable is to_datetime method.

data["end"] = data["end_time"].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d"))
data.info()

Output

    id  end_time    end
0   1   2016-01-13  2016-01-13
1   2   2016-01-01  2016-01-01
2   3   2016-11-12  2016-11-12
3   4   2016-01-17  2016-01-17
4   5   2016-03-13  2016-03-13

Datatypes:

data.info()

Output

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
 #   Column    Non-Null Count  Dtype         
---  ------    --------------  -----         
 0   id        5 non-null      int64         
 1   end_time  5 non-null      object        
 2   end       5 non-null      datetime64[ns]
dtypes: datetime64[ns](1), int64(1), object(1)
memory usage: 248.0+ bytes
Utsav
  • 5,572
  • 2
  • 29
  • 43
  • 1
    You mean *strftime is designed to return a string object*; the one with the **p** is for *parsing* string to datetime, the one with the **f** is for *formatting* datetime to string. – FObersteiner May 08 '21 at 12:32
  • 1
    ahh, my bad. I meant strftime. Updated the explanation. – Utsav May 08 '21 at 12:34