简体   繁体   中英

How can I change format of item in a list?

I try to use google chart and the data format in google chart is like [new Date(2015, 1, 1), 5], [new Date(2015, 1, 2), 7], [new Date(2015, 1, 3), 3]

Clarify(this is what I found in google chart documentation( https://developers.google.com/chart/interactive/docs/datesandtimes#dates-and-times-using-the-date-string-representation ))So base on answer is that mean this format [new Date(2015, 0, 2), 7], could change?:

function drawChart() {

    var data = new google.visualization.DataTable();
    data.addColumn('date', 'Time of Day');
    data.addColumn('number', 'Rating');

    data.addRows([
      [new Date(2015, 0, 1), 5],  [new Date(2015, 0, 2), 7],  [new Date(2015, 0, 3), 3],
      [new Date(2015, 0, 4), 1],  [new Date(2015, 0, 5), 3],  [new Date(2015, 0, 6), 4],
      [new Date(2015, 0, 7), 3],  [new Date(2015, 0, 8), 4],  [new Date(2015, 0, 9), 2],
      [new Date(2015, 0, 10), 5], [new Date(2015, 0, 11), 8], [new Date(2015, 0, 12), 6],
      [new Date(2015, 0, 13), 3], [new Date(2015, 0, 14), 3], [new Date(2015, 0, 15), 5],
      [new Date(2015, 0, 16), 7], [new Date(2015, 0, 17), 6], [new Date(2015, 0, 18), 6],
      [new Date(2015, 0, 19), 3], [new Date(2015, 0, 20), 1], [new Date(2015, 0, 21), 2],
      [new Date(2015, 0, 22), 4], [new Date(2015, 0, 23), 6], [new Date(2015, 0, 24), 5],
      [new Date(2015, 0, 25), 9], [new Date(2015, 0, 26), 4], [new Date(2015, 0, 27), 9],
      [new Date(2015, 0, 28), 8], [new Date(2015, 0, 29), 6], [new Date(2015, 0, 30), 4],
      [new Date(2015, 0, 31), 6], [new Date(2015, 1, 1), 7],  [new Date(2015, 1, 2), 9]
    ]);

and my original data looks like:

x = ['1/4/2014', '2/4/2014','3/4/2014']
z = [100,200,300]

so I try some code:

y=[]
for i in x:
    lastconnection = datetime.strptime(i,"%d/%m/%Y").strftime('%Y,%m,%d')
    y.append((lastconnection))
time = map(lambda x,y:(x,y),y,z)

print time output is:

[('2014,04,01', 100), ('2014,04,02', 200), ('2014,04,03', 300)]

question is I dont know how to add 'new Date()' and put date into bracket without quotation marks. Anyidea?? Thanks in advance!

1) following is the only string format google will accept for dates...

"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"

eg

"Date(2017, 4, 3, 7, 31, 49, 0)"  // <-- 05/03/2017 07:31:49

note: the above string must have the month reduced by one

not all of the arguments are required, this would work as well...

"Date(2017, 4, 3)"  // <-- 05/03/2017 12:00:00

2) however, this format is only accepted by google when using json to build the DataTable

which means the data cannot be in a simple array...

[["Date(2017, 4, 3)", 100]]  // <-- will not work

and must be formatted as follows...

{
  "cols": [
    {"label": "x", "type": "date"},
    {"label": "z", "type": "number"},
  ],
  "rows": [
    {"c":[{"v": "Date(2017, 4, 3)"}, {"v": 100}]}
  ]
}

see following working snippet for an example of using a json string to load the data table...

 google.charts.load('current', { callback: function () { var formatDate = new google.visualization.DateFormat({ pattern: 'MM/dd/yyyy hh:mm:ss' }); var jsonStr = '{"cols": [{"label": "Date", "type": "date"}],"rows": [{"c":[{"v": "Date(2017, 4, 3)"}]}]}'; var data = new google.visualization.DataTable(jsonStr); formatDate.format(data, 0); var container = document.getElementById('chart_div'); var chart = new google.visualization.Table(container); chart.draw(data); }, packages:['table'] }); 
 <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> 


3) if you don't use the above json format...

you will have to massage the data on the client in some manner

you could use arrayToDataTable and a DataView ,

which would allow you to keep the dates in the current format...

 [['1/4/2014', 100], ['2/4/2014', 200], ['3/4/2014', 300]]

in this approach, you would build the data table as-is, then use a data view to convert...

var simpleArr = [['1/4/2014', 100], ['2/4/2014', 200], ['3/4/2014', 300]];

var data = new google.visualization.arrayToDataTable(simpleArr, true); // <-- true = no column headings

var view = new google.visualization.DataView(data);
view.setColumns([
  // convert date column
  {
    calc: function (dt, row) {
      return {
        v: new Date(dt.getValue(row, 0)),
        f: formatDate.formatValue(new Date(dt.getValue(row, 0)))  // <-- formatted value, optional
      }
    },
    label: data.getColumnLabel(0),
    type: 'date'
  },
  // second column requires no manipulation, just use index, instead of calc object
  1
]);

see following working snippet...

 google.charts.load('current', { callback: function () { var formatDate = new google.visualization.DateFormat({ pattern: 'MM/dd/yyyy hh:mm:ss' }); var simpleArr = [['1/4/2014', 100], ['2/4/2014', 200], ['3/4/2014', 300]]; var data = new google.visualization.arrayToDataTable(simpleArr, true); // <-- true = no column headings var view = new google.visualization.DataView(data); view.setColumns([ // convert date column { calc: function (dt, row) { return { v: new Date(dt.getValue(row, 0)), f: formatDate.formatValue(new Date(dt.getValue(row, 0))) // <-- formatted value, optional } }, label: data.getColumnLabel(0), type: 'date' }, // second column requires no manipulation, just use index, instead of calc object 1 ]); var container = document.getElementById('chart_div'); var chart = new google.visualization.Table(container); chart.draw(data); }, packages:['table'] }); 
 <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> 

If you are generating JSON data to be loaded into a google chart in a browser, don't bother with the new Date(..) syntax; that's JavaScript code and not JSON compatible.

Instead, use the supported string notation :

When serializing data using the JavaScript DataTable object literal notation to build your DataTable, the new Date() constructor cannot be used. Instead, Google Charts provides a Date string representation that allows your date or datetime to be serialized and parsed properly when creating a DataTable. This Date string format simply drops the new keyword and wraps the remaining expression in quotation marks:

 "Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)" 

It is not recommended to pass is a string (different browsers parse these differently), so pass in the numeric values and subtract one from the month , as Javascript uses zero-based month values:

date = datetime.strptime(i, "%d/%m/%Y")
lastconnection = 'Date({}, {}, {})'.format(date.year, date.month - 1, date.day)

This then produces:

[("Date(2014, 3, 1)", 100), ("Date(2014, 3, 2')", 200), ("Date(2014, 3, 3)", 300)]

which the Google Chart library then converts to actual Date() objects by evaluating the string with new prepended:

eval("new Date(2014, 3, 1)")
Tue Apr 01 2014 00:00:00 GMT+0100 (BST)

Note that this format is only supported in the DataTable object literal notation .

Google provides a Python library to make this 'easy' to produce, but unfortunately that project is not installable from PyPI (so you'd have to install from the GitHub tarbal instead) and more annoyingly, doesn't support Python 3. The project looks rather dead with no code changes in 4 years and two pull requests withering at the vine.

You have a small problem - new Date() can be only a string in python. If you want to solve this problem as fast as possible - you can use this:

>>> a = 'new Date(1,2,3)'
>>> c = [[a, i] for i in xrange(100,103)]
>>> c
[['new Date(1,2,3)', 100], ['new Date(1,2,3)', 101], ['new Date(1,2,3)', 102]]
>>> c = str(c)
>>> c.replace("'", '')
'[[new Date(1,2,3), 100], [new Date(1,2,3), 101], [new Date(1,2,3), 102]]'

You can save your date as string with 'new Date({0},{1},{2})'.format(...) and use as firs item of sublist. Then convert this list to string and remove all quotes.

Bur I recommend to review your code. May be you'll find a better way to solve the problem (may be with JS or smth).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM