将 datetime.time 转换为字符串

时间:2021-01-20 06:08:21

标签: python python-3.x pandas dataframe data-science

我想将包含时间的标题为“A”的整个列(采用 datetime.time 格式)转换为字符串, 因为我收到错误“TypeError:float() 参数必须是字符串或数字,而不是 datetime.time”

以下是数据:

enter image description here

请建议对代码进行必要的更改/添加。

enter code here
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
load_var=pd.read_excel(r'path\filename.xlsx')
s=load_var.loc[0:11302,['A','B']] 
s1=s
ax.plot(s1[0:11302]['A'],s1[0:11302]['B'],color='orange',linewidth=1.2)
plt.xlabel("A",color='r',fontsize=14)
plt.ylabel("B",color="r",fontsize=14)
plt.title("A Vs B",color="r",fontsize=14)
plt.tick_params(axis='x',which='major',labelsize=7.5,rotation=90)
ax.xaxis.set_major_locator(ticker.MultipleLocator(2))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(1))
plt.grid(True)
plt.ylabel("A",fontsize=14,color="red")
plt.title("A_Vs B",fontsize=14,color="red")
plt.tight_layout()

 

2 个答案:

答案 0 :(得分:1)

试试这个来自 here 的解决方案。这可能就是你要找的:

df["new_col"]= df['A'].astype(str)

答案 1 :(得分:1)

如果数据存储为数据时间,您可能需要先使用 dt.strftime() 将其转换为 HH:MM:SS

import pandas as pd
from datetime import datetime

df = pd.DataFrame({'A':pd.date_range('2017-01-01', freq='10S', periods=6)
                  ,'B':range(1,7)})

print (df)
print (df.info())
#df['A'] = df['A'].astype(str)
df['A'] = pd.to_datetime(df['A']).dt.strftime("%H:%M:%S")

print (df)
print (df.info())

使用 dt.strftime("%H:%M:%S") 会给你:

          A  B
0  00:00:00  1
1  00:00:10  2
2  00:00:20  3
3  00:00:30  4
4  00:00:40  5
5  00:00:50  6

列为:

 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   A       6 non-null      object
 1   B       6 non-null      int64 

如果该列是日期时间格式列并且您使用 astype(str),您将得到以下内容:

                     A  B
0  2017-01-01 00:00:00  1
1  2017-01-01 00:00:10  2
2  2017-01-01 00:00:20  3
3  2017-01-01 00:00:30  4
4  2017-01-01 00:00:40  5
5  2017-01-01 00:00:50  6

列为:

 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   A       6 non-null      object
 1   B       6 non-null      int64 

虽然它确实将其转换为对象(底层是 str),但您可能无法以您想要的格式“%H:%M:%S”获得它。