I am using pandas 1.5.2.
I have a column of timestamp stored in a pandas dataframe.
df['Timestamp'].astype('datetime64[Y]')
0 2017-07-11 09:33:14.819
1 2017-07-11 09:33:14.819
2 2017-07-11 09:33:14.819
3 2017-07-11 09:33:14.819
4 2017-07-11 09:33:14.820
5 2017-07-11 16:20:52.463
6 2017-07-11 16:20:52.463
7 2017-07-11 16:20:52.463
8 2017-07-11 16:20:52.464
9 2017-07-11 16:20:54.984
I used to be able to convert the timestamp to '%Y-%m-%d %H:%M' by df['Timestamp'].astype('datetime64[m]')
. But now this doesn't work and returns the original column.
0 2017-07-11 09:33
1 2017-07-11 09:33
2 2017-07-11 09:33
3 2017-07-11 09:33
4 2017-07-11 09:33
5 2017-07-11 16:20
6 2017-07-11 16:20
7 2017-07-11 16:20
8 2017-07-11 16:20
9 2017-07-11 16:20
CodePudding user response:
I guess you can use the strftime
or to_datetime
package.
df['Timestamp'] = df['Timestamp'].dt.strftime('%Y-%m-%d %H:%M')
Or
df['Timestamp'] = pd.to_datetime(df['Timestamp']).dt.strftime('%Y-%m-%d %H:%M')
CodePudding user response:
You can change a format of the column like this:
import pandas as pd
df = pd.DataFrame({
'Timestamp': ['2017-07-11 09:33:14.819', '2017-07-11 09:33:14.819']
})
print(df)
"""
Timestamp
0 2017-07-11 09:33:14.819
1 2017-07-11 09:33:14.819
"""
df['Timestamp'] = df['Timestamp'].astype('datetime64[m]')
print(df)
"""
Timestamp
0 2017-07-11 09:33:00
1 2017-07-11 09:33:00
"""
If you want to remove the second format, you can convert the value to str
and get only the part you want using slicing
, as follows:
df['Timestamp'] = df['Timestamp'].astype(str).str[0:16]
print(df)
"""
Timestamp
0 2017-07-11 09:33
1 2017-07-11 09:33
"""