Reputation: 79
I am a beginner of Python.
I have the dataframe df_all_data_0
with column time_in
:
2018-01-13 13:17:29
2018-01-06 17:49:43
2018-01-18 09:44:37
2018-01-04 10:45:52
2018-01-11 12:58:31
I want to separate the date (e.g., 2018-01-13) and time (13:17:29). What I tried:
pd.to_datetime(df_all_data_0['time_in']).
date_str = df_all_data_0.strptime('%Y-%m-%d')
But I have en error:
AttributeError Traceback (most recent call last)
<ipython-input-14-d662eee68034> in <module>()
8
9
---> 10 date_str = df_all_data_0.strptime('%Y-%m-%d')
11 #print(type(date_str)) # <class 'str'>
12 #print(date_str) # 2017-10-24
/anaconda/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
2968 if name in self._info_axis:
2969 return self[name]
-> 2970 return object.__getattribute__(self, name)
2971
2972 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'strptime'
How do it correct?
Upvotes: 1
Views: 3018
Reputation: 164623
One way is to use pd.Series.dt.normalize
to extract date with time set to 0 and pd.Series.dt.time
to extract time:
import pandas as pd
from io import StringIO
mystr = StringIO("""2018-01-13 13:17:29
2018-01-06 17:49:43
2018-01-18 09:44:37
2018-01-04 10:45:52
2018-01-11 12:58:31""")
df = pd.read_csv(mystr, sep='|', header=None, names=['DateTime'])
df['DateTime'] = pd.to_datetime(df['DateTime'])
df['Date'], df['Time'] = df['DateTime'].dt.normalize(), df['DateTime'].dt.time
print(df)
# DateTime Date Time
# 0 2018-01-13 13:17:29 2018-01-13 13:17:29
# 1 2018-01-06 17:49:43 2018-01-06 17:49:43
# 2 2018-01-18 09:44:37 2018-01-18 09:44:37
# 3 2018-01-04 10:45:52 2018-01-04 10:45:52
# 4 2018-01-11 12:58:31 2018-01-11 12:58:31
Note the Time
column will have dtype
object:
print(df.dtypes)
# DateTime datetime64[ns]
# Date datetime64[ns]
# Time object
# dtype: object
Upvotes: 2