RSo*_*lis 4 python google-visualization
我正在使用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)
Run Code Online (Sandbox Code Playgroud)
如何使用gviz_api将日期加载到DataTable中?
谷歌文档描述了如何使用javascript创建一个新的Date(),但是,我想继续使用gviz_api.py.
来自https://developers.google.com/chart/interactive/docs/dev/implementing_data_source#jsondatatable 的Google文档中的说明
*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实现使用单引号.*
您可以像在标准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()
Run Code Online (Sandbox Code Playgroud)