简体   繁体   English

Pandas:astype datetime 分钟失败

[英]Pandas: astype datetime minutes failing

I am using pandas 1.5.2.我正在使用 pandas 1.5.2。

I have a column of timestamp stored in a pandas dataframe.我有一列时间戳存储在 pandas dataframe 中。

wall['Timestamp'].astype('datetime64[Y]') wall['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]') .我曾经能够通过df['Timestamp'].astype('datetime64[m]')将时间戳转换为 '%Y-%m-%d %H:%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

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:如果要删除第二种格式,可以将值转换为str并使用slicing仅获取您想要的部分,如下所示:

df['Timestamp'] = df['Timestamp'].astype(str).str[0:16]
print(df)
"""
          Timestamp
0  2017-07-11 09:33
1  2017-07-11 09:33
"""

I guess you can use the strftime or to_datetime package.我猜你可以使用strftimeto_datetime package。

wall['Timestamp'] = wall['Timestamp'].dt.strftime('%Y-%m-%d %H:%M')

Or要么

wall['Timestamp'] = pd.to_datetime(wall['Timestamp']).dt.strftime('%Y-%m-%d %H:%M')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM