2

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
samsegomof
  • 23
  • 3
  • You may need to parse it into a date first. Does your database driver return in native Python form, or just as a string? – tadman Dec 16 '22 at 04:32
  • 1
    To convert a string to a `datetime`, you can either use [`datetime.strptime`](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime) if the format is fixed or [`python-dateutil`](https://pypi.org/project/python-dateutil/2.7.0/) if it's more free format. – Mark Ransom Dec 16 '22 at 04:37
  • я сделал! я просто использовал 'dt': datetime.strptime(obj[0], '%Y-%m-%d').isoformat(), – samsegomof Dec 16 '22 at 04:47
  • Does this answer your question? [Python - Convert string representation of date to ISO 8601](https://stackoverflow.com/questions/4460698/python-convert-string-representation-of-date-to-iso-8601) – Abdul Aziz Barkat Jan 24 '23 at 15:04

0 Answers0