【问题标题】:Use dates from variables使用变量中的日期
【发布时间】:2021-06-22 06:29:38
【问题描述】:

我正在 python3 中编写 python 代码以从 apache solr 获取值。当查询中的日期被硬编码时,该代码运行良好。我想通过在变量中定义日期来传递日期。

这很好用:

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"

预期的查询有什么问题?

【问题讨论】:

    标签: python python-3.x solr


    【解决方案1】:

    您可以使用以下任何一种:

    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=:"

    【讨论】:

    • 不需要 f 字符串,因为可以在 Python 3 的早期版本(以及 2.7 版)中使用 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=:".format(**dict(first_day="2020-10-01", last_day="2020-10-31"))
    【解决方案2】:

    您可以使用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)
    

    【讨论】:

      【解决方案3】:

      变量未正确插入到字符串中。为此,您应该在 python3 中查找 format_strings

      要修复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=:'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-04
        相关资源
        最近更新 更多