【问题标题】:Trying to match today's date with list of custom dates in python试图将今天的日期与 python 中的自定义日期列表相匹配
【发布时间】:2021-06-06 08:18:20
【问题描述】:

尝试将今天的日期与 python 中的自定义日期列表匹配

代码是:

holid = ['2021-01-26', '2021-03-11', '2021-03-29', '2021-04-02', '2021-04-14', '2021-04-21',
 '2021-05-13', '2021-07-21', '2021-08-19', '2021-09-10', '2021-10-15', '2021-11-05','2021-11-19']

date = datetime.today().strftime('%Y-%m-%d')
date

'2021-06-06'

for i in holid:
    i == date
    print("Matched")

它返回错误的输出:

Matched
Matched
Matched
Matched
Matched
Matched
Matched
Matched
Matched
Matched
Matched
Matched
Matched

【问题讨论】:

  • 您正在循环holid,但随后在每次迭代中您打印“匹配”。您的i == date 上缺少if。试试if i == date:(并相应地缩进它下面的行)
  • 另请注意,今天的日期不会出现在列表中。
  • 我的错。我忘了写 if 语句。谢谢大家。

标签: python python-3.x list datetime match


【解决方案1】:

假设您确实想要保留匹配/不匹配的结果,您可以在此处使用列表推导:

holid = ['2021-01-26', '2021-03-11', '2021-03-29', '2021-04-02', '2021-04-14', '2021-04-21', '2021-05-13', '2021-07-21', '2021-08-19', '2021-09-10', '2021-10-15', '2021-11-05','2021-11-19']
date = datetime.today().strftime('%Y-%m-%d')
output = ["Matched" if x == date else "Not Matched" for x in holid]
print(output)

【讨论】:

    【解决方案2】:

    原因是因为最后没有 if 语句所以总是打印匹配,用 if 语句解决这个问题:

    from datetime import datetime
    
    holid = ['2021-01-26', '2021-06-06', '2021-03-11', '2021-03-29', '2021-04-02', '2021-04-14', '2021-04-21',
    '2021-05-13', '2021-07-21', '2021-08-19', '2021-09-10', '2021-10-15', '2021-11-05','2021-11-19']
    
    date = datetime.today().strftime('%Y-%m-%d')
    date
    
    '2021-06-06'
    
    for i in holid:
        if i == date:
            print("Matched")
        else:
            print("Not Matched")
    

    【讨论】:

      猜你喜欢
      • 2019-03-15
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 2014-11-03
      相关资源
      最近更新 更多