1

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"
}
  • Does this answer your question? [What is the "right" JSON date format?](https://stackoverflow.com/questions/10286204/what-is-the-right-json-date-format) – Bracken Nov 12 '21 at 18:15
  • 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. Edit: I wrote up an answer so it's a bit clearer. – rv.kvetch Nov 12 '21 at 18:25

2 Answers2

2

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

Scrapper142
  • 566
  • 1
  • 3
  • 12
0

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.

rv.kvetch
  • 9,940
  • 3
  • 24
  • 53