将字典列表中的日期格式从 MM/DD/YYYY 转换为 YYYY-MM-DDT00:00:00.000Z

Convert the date format from MM/DD/YYYY to YYYY-MM-DDT00:00:00.000Z in a list of dictionaries

我想在示例 HTML 图表中添加我自己的数据。示例数据的javascript代码为:

var data = [];
var visits = 10;
for (var i = 1; i < 50000; i++) {
   visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
   data.push({
       date: new Date(2018, 0, i),
       value: visits
        });
      }

chart.data = data

我用运行输出样本数据console.log(data),发现样本数据是如下字典列表:

[{"date":"2018-11-10T05:00:00.000Z","value":-459},
{"date":"2018-11-11T05:00:00.000Z","value":-459},
{"date":"2018-11-12T05:00:00.000Z","value":-464}, 
...
{"date":"2020-11-22T05:00:00.000Z","value":-493}]

我用 pandas 创建了一个词典列表作为我自己的数据。我更改了自己的数据以匹配上面示例数据列表的格式,以下列表是我自己的数据:

rnow = 
[{'date': '01/02/2020', 'value': 13}, 
{'date': '01/03/2020', 'value': 2}, 
{'date': '01/06/2020', 'value': 5},
...
{'date': '01/07/2020', 'value': 6}]

我意识到日期格式与示例数据不同。我使用以下代码将日期格式更改为 yyyy-mm-dd。

dfrnow['date'] = pd.to_datetime(dfrnow.date)
rnow = dfrnow.to_dict('records')

现在我的数据显示为:

rnow = 
[{'date': Timestamp('2020-01-02 00:00:00'), 'value': 13}, 
{'date': Timestamp('2020-01-03 00:00:00'), 'value': 2}, 
{'date': Timestamp('2020-01-06 00:00:00'), 'value': 5},
...
{'date': Timestamp('2020-01-07 00:00:00'), 'value': 6}]

当我用自己的数据替换示例数据时,图表没有显示任何数据。那是因为它在我的列表中显示了这个“时间戳”东西,我应该如何删除它?或者还有其他更好的方法可以用来转换我的日期吗?

(下面的代码都是这个模板图表的js代码,我把它们都列在这里,以防遗漏。)

var chart = am4core.create("chartdiv", am4charts.XYChart);
chart.paddingRight = 20;

var data = [];
var visits = 10;
for (var i = 1; i < 50000; i++) {
  visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
       data.push({
           date: new Date(2018, 0, i),
            value: visits
            });
      }

chart.data = {{rnow}};

var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.minZoomCount = 5;

dateAxis.groupData = true;
dateAxis.groupCount = 500;

var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";
series.tooltipText = "{valueY}";
series.tooltip.pointerOrientation = "vertical";
series.tooltip.background.fillOpacity = 0.5;

chart.cursor = new am4charts.XYCursor();
chart.cursor.xAxis = dateAxis;

var scrollbarX = new am4core.Scrollbar();
scrollbarX.marginBottom = 20;
chart.scrollbarX = scrollbarX;

var selector = new am4plugins_rangeSelector.DateAxisRangeSelector();
selector.container = document.getElementById("selectordiv");
selector.axis = dateAxis;           

我通过以下方式解决了它:

rnow = dfrnow.to_dict('records')
    def new_date(date):
        return datetime.strptime(date, '%m/%d/%Y').strftime('%Y-%m-%dT00:00:00Z')
    for i in range (len(rnow)):
        rnow[i]['date'] = new_date(rnow[i]['date'])