我正在使用gviz_api(google-visualization-python)来构建一些折线图。 http://code.google.com/p/google-visualization-python/
我编辑了一个从谷歌文档中获取的折线图示例 但是,我不确定如何将日期传递给DataTable
这是我一直在使用的编辑过的示例。 https://gist.github.com/3941946
以下是我对
提出问题的代码 # Creating the data
description = {"year": ("string", "Year"),
"sales": ("number", "Sales"),
"expenses": ("number", "Expenses")}
data = [{"year": '2004', "sales": 1000, "expenses": 300},
{"year": '2005', "sales": 1200, "expenses": 400},
{"year": '2006', "sales": 1300, "expenses": 500},
{"year": '2007', "sales": 1400, "expenses": 600},
{"year": '2008', "sales": 1500, "expenses": 800}]
# Loading it into gviz_api.DataTable
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
如何使用gviz_api将日期加载到DataTable中?
Google文档介绍了如何使用javascript创建新的Date(),但是,我想继续使用gviz_api.py。
来自Google文档的说明 来自https://developers.google.com/chart/interactive/docs/dev/implementing_data_source#jsondatatable
* JSON修改 Google的帮助程序库以及发送给Google的所有查询都会返回略微非标准版本的JSON / JSONP。如果您没有自己解析返回的代码,这对您来说无关紧要。 Visualization API客户端支持JSON的标准版本和修改版本。以下是差异的摘要:
JSON不支持JavaScript Date值(例如,“new Date(2008,1,28,0,31,26)”; API实现可以。但是,API现在支持自定义的有效JSON表示形式以下列格式将日期作为字符串:日期(年,月,日[,小时,分钟,秒[,毫秒]]),其中一天之后的所有内容都是可选的,而月份则从零开始。
JSON对字典键使用双引号; API实现使用不带引号的密钥。
JSON需要围绕字符串值使用双引号; API实现使用单引号。*
答案 0 :(得分:5)
您实际上可以像处理标准Python一样处理创建日期 - API会为您处理转换为JS。您只需在脚本开头import datetime
,将year
的列类型从string
更改为date
,然后按照标准创建日期的Python:
# This is the first modification - importing the library
import datetime
import gviz_api
# page_template stays the same
# ...
def main():
# Creating the data
# Here we change the type of column "year" to "date"
description = {"year": ("date", "Year"),
"sales": ("number", "Sales"),
"expenses": ("number", "Expenses")}
# Here we switch out the string dates with an actual Python datetime.date
# The conversion happens in the the subsequent functions, giving you a
# date that is usable in the JS
data = [{"year": datetime.date(2007,3,7), "sales": 1000, "expenses": 300},
{"year": datetime.date(2009,6,11), "sales": 1200, "expenses": 400},
{"year": datetime.date(2009,3,1), "sales": 1300, "expenses": 500},
{"year": datetime.date(2010,8,6), "sales": 1401, "expenses": 600},
{"year": datetime.date(2011,7,13), "sales": 1500, "expenses": 800}]
# Loading it into gviz_api.DataTable
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
# Creating a JavaScript code string
jscode = data_table.ToJSCode("jscode_data",
columns_order=("year", "sales", "expenses"),
order_by="year")
# Creating a JSon string
json = data_table.ToJSon(columns_order=("year", "sales", "expenses"),
order_by="year")
# Putting the JS code and JSon string into the template
print "Content-type: text/html"
print
print page_template % vars()
if __name__ == '__main__':
main()