Home > Enterprise >  How I can reformat dates to ISO format in my code?
How I can reformat dates to ISO format in my code?

Time:12-17

I have a function which get data from database and reformat they in JSON file, but I need date fields was a ISO format - "dt": "2022-12-01T00:00:00". In code this fields named 'dt'.

    def table_to_json():
        db_connect = Database('database_name')
        query = '''SELECT * FROM table_name'''
        data = db_connect.get_query_result(query).fetchall()
        res = {'fields': {'data': []}}
        for obj in data:
            res['fields']['data'].append(
                {
                            'field_1': obj[1],
                            'dt': obj[0],
                            'field_2': obj[2],
                            'field_3': obj[3],
                            'field_4': obj[4],
                            'field_5': obj[5]
                        }
            )
    
        with open("my_file.json", "w") as file:
            json.dump(res, file)

Im tryed use datetime.isoformat(obj[0]), but dates is str objects and isoformat() working with int and datetime formats how i understand.

CodePudding user response:

You can use the datetime module to reformat the date field dt in ISO format.

import datetime

def table_to_json():
    db_connect = Database('database_name')
    query = '''SELECT * FROM table_name'''
    data = db_connect.get_query_result(query).fetchall()
    res = {'fields': {'data': []}}
    for obj in data:
        # Convert the date field 'dt' to a datetime object
        dt = datetime.datetime.strptime(obj[0], '%Y-%m-%d')
        # Format the datetime object in ISO format
        iso_dt = dt.isoformat()
        res['fields']['data'].append(
            {
                        'field_1': obj[1],
                        'dt': iso_dt,
                        'field_2': obj[2],
                        'field_3': obj[3],
                        'field_4': obj[4],
                        'field_5': obj[5]
                    }
        )

    with open("my_file.json", "w") as file:
        json.dump(res, file)

  • Related