【问题标题】:Comparing two lists containing dates in Python在 Python 中比较两个包含日期的列表
【发布时间】:2018-02-21 09:57:16
【问题描述】:

我有两个函数dte() 和生成dates(),它们都打印特定范围内的日期。

def dte(): 
    date = (' '.join(map(str,ddt)))      
    return date

print dte()


def generate_dates(start_date, end_date):
    td = datetime.timedelta(hours=24)
    current_date = start_date
    while current_date <= end_date:
        print current_date
        current_date += td
    start_date = datetime.date(2017, 10, 25)
    end_date = datetime.date(2017, 10, 28)

dte() 包含一些缺失的日期,而generate_dates() 是完整的。如何比较它们并将缺失值存储在另一个列表中为 0 ?

例如:[2017-10-25 , 0 , 2017-10-27 , 0 , 0 , 2017-10-30...]

编辑:这是我打印这两个函数时的输出:

('2017-07-26',) ('2017-07-27',) ('2017-07-28',) ('2017-07-29',)       ('2017-07-30',) ('2017-07-31',) ('2017-08-01',) ('2017-08-02',) ('2017-08-03',) ('2017-08-04',) ('2017-08-05',) ('2017-08-08',) ('2017-08-09',) ('2017-08-10',) ('2017-08-11',) ('2017-08-12',) ('2017-08-14',) ('2017-08-16',) ('2017-08-17',) ('2017-08-18',) ('2017-08-19',) ('2017-08-21',) ('2017-08-22',) ('2017-08-23',) ('2017-08-24',)

2017-07-26
2017-07-27
2017-07-28
2017-07-29
2017-07-30
2017-07-31
2017-08-01
2017-08-02
2017-08-03
2017-08-04
2017-08-05
2017-08-06
2017-08-07
2017-08-08
2017-08-09
2017-08-10
2017-08-11
2017-08-12
2017-08-13
2017-08-14
2017-08-15
2017-08-16
2017-08-17
2017-08-18
2017-08-19
2017-08-20
2017-08-21
2017-08-22
2017-08-23
2017-08-24

【问题讨论】:

  • 欢迎来到 SO!你能给我们一些数据吗?理想情况下,需要有代表性的输入和输出。另请阅读:minimal reproducible example.
  • 编辑中添加的输出。

标签: python list


【解决方案1】:

这是一个使用您自己的代码的简单示例:

import datetime

ddt = [
    datetime.date(2017,10,25),
    datetime.date(2017,10,27),
    datetime.date(2017,10,28),
]

def generate_dates(start_date, end_date):
    res = []
    td = datetime.timedelta(hours=24)
    current_date = start_date
    while current_date <= end_date:
        res.append(current_date)
        current_date += td
    return res

start_date = datetime.date(2017, 10, 25)
end_date = datetime.date(2017, 10, 30)

all_dates = generate_dates(start_date, end_date)

res = []
for date in all_dates:
    if date not in ddt:
        res.append(0)
    else:
        res.append(date)

print map(str, res)

输出:

['2017-10-25', '0', '2017-10-27', '2017-10-28', '0', '0']

请注意,我更改了 generate_dates() 函数以返回完整的日期范围(不仅仅是打印它们)。

另请注意,此代码不是最优的。它将具有 O(N*M) 的复杂度,其中 N - 大小为 ddt,M - 大小为 all_dates。所以它绝对不是大型列表的最佳选择。如果您的列表ddt 很大,您可能希望在最后一个循环之前将其转换为一个集合:

ddt = set(ddt)

这样复杂度将是 O(M)。

【讨论】:

  • 我试过这个方法,但是当月份小于10时它不起作用,例如。由于数据库中的日期返回为 ['2017-07-26', '2017-07-27'] 并且 datetime 函数中的日期返回为 [datetime.date(2017, 7, 26), datetime.date(2017, 7, 27), datetime.date(2017, 7, 28), datetime.date(2017, 7, 29),返回的输出是['0','0','0'..]
  • @Justinj64,您需要将字符串中包含的日期转换为 date 对象。你可以这样做:ddt = map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').date(), ddt)
猜你喜欢
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2022-01-08
  • 2017-04-28
  • 1970-01-01
  • 2018-02-17
  • 2013-12-20
相关资源
最近更新 更多