Skip to content

Commit a788ea1

Browse files
committed
BigQuery: named parameter timestamp sample
An example query using timestamps in named parameters. See: https://cloud.google.com/bigquery/querying-data#using_timestamps_in_parameterized_queries
1 parent 547041e commit a788ea1

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
google-cloud-bigquery==0.22.1
2+
pytz==2016.10

bigquery/cloud-client/sync_query_params.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@
2424
"""
2525

2626
import argparse
27+
import datetime
2728

29+
import pytz
2830
from google.cloud import bigquery
2931

3032

@@ -109,6 +111,20 @@ def sync_query_array_params(gender, states):
109111
print_results(query_results)
110112

111113

114+
def sync_query_timestamp_params():
115+
client = bigquery.Client()
116+
query_results = client.run_sync_query(
117+
'SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);',
118+
query_parameters=[
119+
bigquery.ScalarQueryParameter(
120+
'ts_value',
121+
'TIMESTAMP',
122+
datetime.datetime(2016, 12, 7, 8, tzinfo=pytz.UTC))])
123+
query_results.use_legacy_sql = False
124+
query_results.run()
125+
print_results(query_results)
126+
127+
112128
if __name__ == '__main__':
113129
parser = argparse.ArgumentParser(
114130
description=__doc__,
@@ -145,6 +161,9 @@ def sync_query_array_params(gender, states):
145161
'states',
146162
help='U.S. States to consider for popular baby names.',
147163
nargs='+')
164+
timestamp_parser = subparsers.add_parser(
165+
'timestamp',
166+
help='Run a query with a timestamp parameter.')
148167
args = parser.parse_args()
149168

150169
if args.sample == 'named':
@@ -153,5 +172,7 @@ def sync_query_array_params(gender, states):
153172
sync_query_positional_params(args.corpus, args.min_word_count)
154173
elif args.sample == 'array':
155174
sync_query_array_params(args.gender, args.states)
175+
elif args.sample == 'timestamp':
176+
sync_query_timestamp_params()
156177
else:
157178
print('Unexpected value for sample')

bigquery/cloud-client/sync_query_params_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ def test_sync_query_array_params(cloud_config, capsys):
2323
assert 'James' in out
2424

2525

26+
def test_sync_query_array_params(cloud_config, capsys):
27+
sync_query_params.sync_query_timestamp_params()
28+
out, _ = capsys.readouterr()
29+
assert '2016-12-07 09:00:00' in out
30+
31+
2632
def test_sync_query_named_params(cloud_config, capsys):
2733
sync_query_params.sync_query_named_params(
2834
corpus='romeoandjuliet',

0 commit comments

Comments
 (0)