为什么date-time会自动更改为object数据类型?

时间:2020-12-02 17:00:59

Need to convert object type to Date-time and use that converted date-time is unknowingly changed to the object again while filtering.

需要将对象类型转换为日期时间并使用转换后的日期时间在过滤时不知不觉地再次更改为对象。

msft['Tested On'] = pd.to_datetime(msft['Tested On'])
msft['Tested On'].dt.date
df = msft[msft['Tested On'] == '2018-02-02']

Actual result: TypeError: 'NoneType' object is not subscriptable

实际结果:TypeError:'NoneType'对象不可订阅

Expected result: Need to display the filtered list with the other rows and columns also

预期结果:还需要显示已过滤列表以及其他行和列

1 个解决方案

#1


0  

I think you need to_datetime and if first digit is day, add parameter dayfirst=True:

我认为你需要to_datetime,如果第一个数字是天,添加参数dayfirst = True:

print (msft)
  Title plan     run   status           Tested On
0     A   P0      P0   Passed  11/08/2018 8:42 AM
1     B   P0      P0   Failed  12/08/2018 8:42 AM
2     C    -  Canary   Passed  10/08/2018 8:42 AM
3     D    -  Sanity  Blocked  11/08/2018 8:42 AM

msft['Tested On'] = pd.to_datetime(msft['Tested On'], dayfirst=True)
print (msft)
  Title plan     run   status           Tested On
0     A   P0      P0   Passed 2018-08-11 08:42:00
1     B   P0      P0   Failed 2018-08-12 08:42:00
2     C    -  Canary   Passed 2018-08-10 08:42:00
3     D    -  Sanity  Blocked 2018-08-11 08:42:00

Then remove times by dt.floor and compare:

然后通过dt.floor删除时间并比较:

df = msft[msft['Tested On'].dt.floor('d') == '2018-08-11']
print (df)
  Title plan     run   status           Tested On
0     A   P0      P0   Passed 2018-08-11 08:42:00
3     D    -  Sanity  Blocked 2018-08-11 08:42:00

Detail:

print (msft['Tested On'].dt.floor('d'))
0   2018-08-11
1   2018-08-12
2   2018-08-10
3   2018-08-11
Name: Tested On, dtype: datetime64[ns]

#1


0  

I think you need to_datetime and if first digit is day, add parameter dayfirst=True:

我认为你需要to_datetime,如果第一个数字是天,添加参数dayfirst = True:

print (msft)
  Title plan     run   status           Tested On
0     A   P0      P0   Passed  11/08/2018 8:42 AM
1     B   P0      P0   Failed  12/08/2018 8:42 AM
2     C    -  Canary   Passed  10/08/2018 8:42 AM
3     D    -  Sanity  Blocked  11/08/2018 8:42 AM

msft['Tested On'] = pd.to_datetime(msft['Tested On'], dayfirst=True)
print (msft)
  Title plan     run   status           Tested On
0     A   P0      P0   Passed 2018-08-11 08:42:00
1     B   P0      P0   Failed 2018-08-12 08:42:00
2     C    -  Canary   Passed 2018-08-10 08:42:00
3     D    -  Sanity  Blocked 2018-08-11 08:42:00

Then remove times by dt.floor and compare:

然后通过dt.floor删除时间并比较:

df = msft[msft['Tested On'].dt.floor('d') == '2018-08-11']
print (df)
  Title plan     run   status           Tested On
0     A   P0      P0   Passed 2018-08-11 08:42:00
3     D    -  Sanity  Blocked 2018-08-11 08:42:00

Detail:

print (msft['Tested On'].dt.floor('d'))
0   2018-08-11
1   2018-08-12
2   2018-08-10
3   2018-08-11
Name: Tested On, dtype: datetime64[ns]