D
D
Danil Samodurov2021-03-27 18:14:41
Python
Danil Samodurov, 2021-03-27 18:14:41

Is there a way to convert dates from string type to datetame while parsing json to html?

Hello. I'm pulling json as a list of dictionaries by url on the web via requests.get(url, timeout=1).json(). Each dictionary has a key 'date' with a date value. When parsing, the date remains in the 'str' type. To convert all dates to datetime, you can use a loop to convert dates like this: datetime.strptime(str_date, "%Y-%m-%d %H:%M:%S"). Is there a way to convert dates during parsing? Maybe some attribute in get() or json() responsible for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shurshur, 2021-03-27
@shurshur

import json
import datetime

test = '[{"date":"2000-01-01 00:00:00","foo":"bar"},{"date":"2022-12-31 23:59:59","lorem":"ipsum"}]'

def hook(pairs, format="%Y-%m-%d %H:%M:%S"):
  d = {}
  for k, v in pairs:
    #if isinstance(v, basestring):
    if k == "date":
      try:
        d[k] = datetime.datetime.strptime(v, format)
      except ValueError:
        d[k] = v
    else:
      d[k] = v
  return d

print (json.loads(test, object_pairs_hook=hook))

Idea peeped here: https://stackoverflow.com/a/14996040

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question