Home > other >  export data to csv in class from class python
export data to csv in class from class python

Time:12-28

I have a python code that is used to pull data from azure methods.

for item in response:

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

below is the print statements 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. How can I do that with correct date format as well. can you please help me?

CodePudding user response:

Try this if you want to store all rows in the response to one CSV file.

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.

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

Here is the content of the CSV file.

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.

CodePudding user response:

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. then you can convert it to csv file with to_csv.

  • Related