使用pandas read_gbq将日期字符串传递给函数无法识别

时间:2016-11-04 15:45:20

标签: python pandas google-bigquery

您好,感谢您花时间阅读.... 日期字符串(即date_start)似乎已根据两个打印功能成功传递到函数中。输出(遵循下面的代码)但它不被识别为where子句中的日期,因为结果集为null(当使用硬编码的日期字符串文字时,结果集在函数外不是null。

date_start = '2016-10-14 09:00:00'
    def get_recs_w_date_range(date_l):
      "Iterate through various date ranges to create the a timeframe sample for later aggregation"
    global df1
    global date_g
    date_g = date_l
    df1 = pd.read_gbq("select Timestamp, bytes, dst_addr, cast(dst_port as integer) as dst_port, \
    cast(duration_ms as integer) as duration_ms, protocol, flow_direction \
    FROM ipfix.ipfix \
     where Timestamp between timestamp('date_l') and timestamp('2016-10-14 09:00:30') limit 50",
              project_id="network-sec-analytics")
    print('The value of local var date_l is: {}'.format(date_l))
return

get_recs_w_date_range(date_start) 

print('The value of global var date_g is: {}'.format(date_g))

df1

    The value of local var date_l is: 2016-10-14 09:00:00
    The value of global var date_g is: 2016-10-14 09:00:00

1 个答案:

答案 0 :(得分:1)

好的,我觉得这很容易解决。您需要将date_l的值归结为您未查询的查询。试试这个:

def get_recs_w_date_range(date_l):
    """Iterate through various date ranges to create the a timeframe sample for later aggregation"""
    query = """SELECT Timestamp, bytes, dst_addr,
                 cast(dst_port as integer) as dst_port,
                 cast(duration_ms as integer) as duration_ms,
                 protocol, flow_direction 
               FROM ipfix.ipfix
               WHERE Timestamp BETWEEN timestamp('{}') AND
                 timestamp('2016-10-14 09:00:30')
               LIMIT 50""".format(date_l)
    return pd.read_gbq(query, project_id="network-sec-analytics")

format方法会将{}替换为date_l的值。您的查询现在应该可以使用。