Home > OS >  How to specify date as a data type in json
How to specify date as a data type in json

Time:11-13

I'm building a parquet converter in python that takes in a json with the fields and the dtypes of those fields. How do I classify a field that has a data type as date in a json?

{
  "contact_firstname": "string",
  "contact_suffix": "string",
  "contact_middle_name": "string",
  "contact_email_address": "string",
  "contact_date_of_birth": "datetime",
  "contact_address_line_2": "string",
  "contact_address_line_3": "string"
}

CodePudding user response:

JSON can only take dicts, lists, bools and numbers. So you can't directly store a date in it. So you would actually just store the date in a string, then the program reading the json would have to know to turn the string into a date

CodePudding user response:

Use the result of date.isoformat(), which is a string, in the JSON object. When deserializing the object, use date.fromisoformat() to convert string to a date.

from datetime import date

date_string = date.min.isoformat()
print(date_string)     # 0001-01-01
date_obj = date.fromisoformat(date_string)
print(repr(date_obj))  # datetime.date(1, 1, 1)

Alternatively, you can also store the date as a number in the JSON object (as a UNIX timestamp, representing total seconds since the epoch). Then similarly use date.fromtimestamp() to convert the timestamp value to a date object.

  • Related