Skip to main content
 首页 » 编程设计

python之时间戳日期格式无法转换为 float

2024年09月07日9arxive

我一直在尝试将下面的日期从时间戳转换为 float 。我已经尝试了所有命令中的所有功能(fromtimestamp、strftime、strptime、.date()...等等),但什么也没有。我还阅读了谷歌上提供的所有相关问题,但没有一个对我有用。有人可以帮忙吗?

最接近我得到的解决方案是下面的代码和错误状态:“TypeError:需要一个整数(得到类型时间戳)”并且我相信在此之后会弹出其他错误。

可以在这里找到导入的文件:

https://www.dropbox.com/s/oe0h7mu2k0vwpn2/Linx%20Revenues.xls?dl=0

import pandas as pd 
import datetime 
 
#Upload Data 
df = pd.read_excel("Linx Revenues.xls") 
 
#Rename Columns 
df.columns = ['Date', 'Gross'] 
 
#Adjust Dates 
 
for index, row in df.iterrows(): 
 
df['Date'][index] = datetime.datetime(df['Date'][index], '%d/%m/%y').date().strftime('%d/%m/%Y')              
df["Date"][index] = float(datetime.strptime(df["Date"][index], '%d/%m/%Y').date().strftime('%Y%m%d')) 

请您参考如下方法:

我想你需要strftime用于 astype 的字符串格式转换为float:

df["Date"] = pd.to_datetime(df["Date"], '%d/%m/%Y').dt.strftime('%Y%m%d').astype(float) 

使用真实数据的解决方案很简单,因为没有必要转换为日期时间:

df = pd.read_excel('Linx Revenues.xls') 
df.columns = ['Date', 'Gross'] 
#print (df) 
 
df["Date"] = df["Date"].dt.strftime('%Y%m%d').astype(float) 
print (df) 
          Date    Gross 
0   20171201.0   168.40 
1   20171201.0   188.60 
2   20171201.0   177.40 
3   20171201.0   958.90 
4   20171201.0   931.90 
5   20171201.0    71.80 
6   20171201.0    35.00 
7   20171201.0   556.13 
8   20171201.0   413.00 
9   20171201.0     0.90 
10  20171201.0   699.00 
11  20171201.0   111.70 
12  20171201.0   153.30 
13  20171201.0   669.10 
14  20171201.0   713.70 
15  20171201.0   423.70 
16  20171201.0    -2.00 
17  20171202.0    80.50 
18  20171202.0   213.40 
19  20171202.0  1170.10 
20  20171202.0   605.00 
21  20171202.0  1275.30 
22  20171202.0   202.30 
23  20171202.0   120.00