使用变量中的日期

ckocjqey  于 2021-10-10  发布在  Java
关注(0)|答案(3)|浏览(205)

我正在用python3编写一个python代码,以从apachesolr获取值。当查询中的日期是硬编码的时,代码工作良好。我想通过在变量中定义日期来传递日期。
这很有效:

query='http://x.x.x.x:8983/solr/test/select?fq=timestamp:%5b2020-10-01T00:00:00.000Z%20TO%202020-10-31T23:59:59.999Z%5d&q=*:*'

预期:

query='http://x.x.x.x:8983/solr/test/select?fq=timestamp:%5b'first_dayT00:00:00.000Z%20TO%20'last_day'T23:59:59.999Z%5d&q=*:*'

first_day = "2020-10-01"

last_day = "2020-10-31"

预期的查询有什么问题?

e0bqpujr

e0bqpujr1#

您可以使用以下任一选项:

first_day = "2020-10-01"
last_day = "2020-10-31"

使用字符串连接
query = "http://x.x.x.x:8983/solr/test/select?fq=timestamp:%5b" + first_day + "T00:00:00.000Z%20TO%20" + last_day + "T23:59:59.999Z%5d&q=:" f string -仅适用于python 3.6及更高版本 query = f"http://x.x.x.x:8983/solr/test/select?fq=timestamp:%5b{first_day}T00:00:00.000Z%20TO%20{last_day}T23:59:59.999Z%5d&q=:"

bqf10yzr

bqf10yzr2#

你可以用 f-string 将变量插入字符串的步骤

query = f'http://x.x.x.x:8983/solr/test/select?fq=timestamp:%5b{first_day}T00:00:00.000Z%20TO%20{last_day}T23:59:59.999Z%5d&q=:'

或使用 format() ```
query = 'http://x.x.x.x:8983/solr/test/select?fq=timestamp:%5b{}T00:00:00.000Z%20TO%20{}T23:59:59.999Z%5d&q=:'.format(first_day, last_day)

yhived7q

yhived7q3#

变量未正确插入字符串中。为此,您应该在python3中查找format_字符串。
用于修复 query ,你可以这样做

query=f'http://x.x.x.x:8983/solr/test/select?fq=timestamp:%5b{first_day}T00:00:00.000Z%20TO%20{last_day}T23:59:59.999Z%5d&q=:'

相关问题