How to manipulate Date attribute from a Python Json result

Asked

Viewed 625 times

-1

I have a Json output that I am using in a Google Sheets spreadsheet, and with this information I need to sort them by Date, so I need to get this date into the separate Date and Time spreadsheet like this:

Question how to split this date: "2019-07-22T16:00:04.8579075" and turn it into Date & Time as below

Date 22/07/2019

Time 16:00

[
    {
        ordemChegadaId: 1,
        data: "2019-07-22T16:00:04.8579075",
        veiculoId: 29,
        nome: "J G DO VALE - TRANSPORTES ME"
    },
    {
        ordemChegadaId: 2,
        data: "2019-07-22T16:30:02.8375000",
        veiculoId: 29,
        nome: "AVES - TRANSPORTES ME"
    },
    . . .
]

Python script responsible for sending information to Google Sheets

function IMPORTJSON(url){

  try{
    // /rates/EUR
    var res = UrlFetchApp.fetch(url);
    var content = res.getContentText();
    var json = JSON.parse(content);

    if(typeof(json) === "undefined")
    {
      return "Node Not Available";
    } 
    else if(typeof(json) === "object")
    {
      var tempArr = [];

      for(var obj in json)
      {
        //datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')
        tempArr.push([json[obj].data, json[obj].ordem, json[obj].veiculoId, json[obj].getVeiculo.motorista]);

      }
      return tempArr;
    } 
    else if(typeof(json) !== "object") 
    {
      return json;
    }


  }
  catch(err){
      return "Error getting data";  
  }

} 
  • 1

    You know this script is Javascript, right? I was working out an answer with Python here, the answers that already exist are incomplete, but they are also Python. If you can’t change where you’re using the script, it won’t help.

2 answers

0

convert the JSON date can do as per the code below.
I left to glory in the code’s comments and not here in the answer to make it easier to understand.

import json;
import datetime;

dados = '{"ordemChegadaId": 1,"data": "2019-07-22T16:15:04.8579075", "veiculoId": 29, "nome": "J G DO VALE - TRANSPORTES ME"}';
//Aqui estou transformando a String dados em um objeto JSON 
dadosJsonFormat = json.loads(dados);

dateTimeStr = dadosJsonFormat["data"];
//Como a data que veio no JSON vem como string então precisamos converter de string para datetime.
dateTimeObj = datetime.datetime.strptime(dateTimeStr[0:-1], '%Y-%m-%dT%H:%M:%S.%f');
//Depois de convertido para datetime é só utilizar o método format para criar a data e hora
data = '{}/{}/{}'.format(dateTimeObj.day,dateTimeObj.month,dateTimeObj.year);
hora = '{}:{}'.format(dateTimeObj.hour,dateTimeObj.minute);

print(data,hora);

Important
Note that when converting the string to datetime I used %Y-%m-%dT%H:%M:%S.%f to map your string, see that by separating the time date in your JSON comes the character T and into the second and thousandth of a second comes the character . , they need to be in this mapping too.
Another detail is that in your JSON the millionths of a second field comes with 7 positions and the function strptime accepts at most 6 in this parameter, so I had to remove the last one with the code dateTimeStr[0:-1]

You can test this code using the website repl it.

EDITED Here is the code using regx only You don’t need to put import json in your code, because you already have your json variable that has this content, just use dateTimeStr = dadosJsonFormat["data"]; down.

import json;

dados = '{"ordemChegadaId": 1,"data": "2019-07-22T16:15:04.8579075", "veiculoId": 29, "nome": "J G DO VALE - TRANSPORTES ME"}';

dadosJsonFormat = json.loads(dados);

dateTimeStr = dadosJsonFormat["data"];

data = '{}/{}/{}'.format(dateTimeStr[8:10],dateTimeStr[5:7],dateTimeStr[0:4]);
hora = '{}:{}'.format(dateTimeStr[11:13],dateTimeStr[14:16]);

print(data,hora);
  • I’m using the Google Script editor because this script passes this information to Google Sheets and the library imports don’t work, so this is the problem, these import json; import datetime; I can’t add.

  • It is not easier to use the datetime.fromisoformat()? Example: data = datetime.datetime.fromisoformat(dateTimeStr[:-1])

  • Then you’ll need to use regx only, I’ll edit my answer to help you

  • @Cyberlacs think that now you can use without problem, remembering that that import json you don’t need because you already have the json, I had to use it to turn the string into a json.

0

You can format with Python’s buit-in datetime and use the method strptime(date, Formatacao)

for example: if you are receiving a date object -> 2016-09-22

from datetime import datetime

data = '2016-09-22'
# pegar os primeiros 10 caracteres e converter 
# para objeto date no formato ano/mes/dia
data_formatada = datetime.strptime(data, '%Y-%m-%d')
print("Data: ", type(data_formatada)) # Data:  <class 'datetime.datetime'>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.