简体   繁体   English

从 class python 导出数据到 class 中的 csv

[英]export data to csv in class from class python

I have a python code that is used to pull data from azure methods.我有一个 python 代码,用于从 azure 方法中提取数据。

for item in response:

    print(type(item))
    print(item)
    df = pd.DataFrame([item])
    print(df)

below is the print statements output.下面是打印报表 output。

 1. print(type(item)) :
     <class 'azure.mgmt.costmanagement.models._models_py3.SavingsPlanUtilizationSummary'>



2.print(item) : 
{'usage_date': datetime.datetime(2022, 12, 26, 0, 0, tzinfo=<isodate.tzinfo.Utc object at 0x00000277D15A2D60>), 'avg_utilization_percentage': 95.83333333039417, 'min_utilization_percentage': 0.0}

3.print(df):
                                                   0
0  {'usage_date': datetime.datetime(2022, 12, 26, 0, 0, tzinfo=<isodate.tzinfo.Utc object at 0x00000277D15A2D60>), 'avg_utilization_percentage': 95.83333333039417, 'min_utilization_percentage': 0.0}

Above Output I am getting but I am trying to export data into csv with different columns.在 Output 以上,我正在尝试将数据导出到具有不同列的 csv。 How can I do that with correct date format as well.我怎样才能用正确的日期格式来做到这一点。 can you please help me?你能帮我么?

Try this if you want to store all rows in the response to one CSV file.如果您想将所有行存储在对一个 CSV 文件的响应中,请试试这个。

usage_statistics = pd.DataFrame([row for row in response])
usage_statistics.to_csv('output.csv', index=False)

You can also use date_format parameter to format datetime objects as you want.您还可以根据需要使用date_format参数来格式化datetime对象。

usage_statistics.to_csv('output.csv', date_format='%Y%m%d', index=False)

Here is the content of the CSV file.这是 CSV 文件的内容。

usage_date,avg_utilization_percentage,min_utilization_percentage
2022-12-26,95.83333333039417,0.0

Refer to the official document: strftime() and strptime() Behavior for the codes of the format string.格式字符串的代码参考官方文档: strftime()和strptime()Behavior

The problem here is that you are not formatting usage_date when importing data from Azure. When importing data from azure, please convert datetime to dataframe after .strftime("%Y-%m-%d") it will be fine.这里的问题是你从Azure导入数据的时候没有格式化usage_date 。从azure导入数据的时候,请在.strftime("%Y-%m-%d")之后将datetime转为dataframe就可以了。 then you can convert it to csv file with to_csv .然后您可以使用 to_csv 将其转换为to_csv文件。

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

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