Using timestamp, json e python

148 views Asked by At

This script makes the requisition fligts google every 1h, using time.sleep (3600) and generates a txt file with all phrases he rolled over a day and a half. I want do this properly using TIMESTAMP. Someone can help me?

import urllib
import urllib2
import json
import time

while 1:
    url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyA3758yM14aTX7aI9_v5AvKI2X1m56HszI" 

    code = {

    "request": {
    "passengers": {
      "adultCount": 1,
      "childCount": 1
     },
    "slice": [
      {
        "origin": "SSA",
        "destination": "GRU",
        "date": "2015-06-19",
        "permittedDepartureTime":
        {
          "kind": "qpxexpress#timeOfDayRange",
          "earliestTime": "22:00",
          "latestTime": "23:00"
        }
      },
      {
        "origin": "GRU",
        "destination": "SSA",
        "date": "2015-06-30",
        "permittedDepartureTime":
        {
          "kind": "qpxexpress#timeOfDayRange",
          "earliestTime": "05:00",
          "latestTime": "12:00"
        }
      }
    ],
    "solutions": 3
      }
    }

    #hoje = "%s" % (time.strftime("%Y_%m_%d")) 

    jsonreq = json.dumps(code, encoding = 'utf-8')
    req = urllib2.Request(url, jsonreq, {'Content-Type': 'application/json'})
    flight = urllib2.urlopen(req)
    response = flight.read()
    flight.close()
    #print(response)
    print("----------------")


    texto=(response)
    v_file= open("ssaGRU.json" ,"a")

    #hora = time.strftime("%H:%M:%S %Z")
    v_file.write(texto)
    #v_file.write("[%s] Hora do json.\r\n" % (hora)) 
    v_file.close()

    time.sleep(15)
1

There are 1 answers

0
Leb On
current_time = time.strftime("%H:%M", time.localtime())
v_file = open("ssaGRU.json", "a")
v_file.write(str(current_time) + ': ')
v_file.write(texto + '\n')
v_file.close()

This will print your current time before every line inputted, and adds a an empty line at the end so your data from different times doesn't stay on one line.

You can also add %m.%d.%y to current_time if you need. In case texto isn't a string, make sure you add str(texto).