【问题标题】:Sort list of Person based on Birthday from current date python?根据当前日期python的生日对人员列表进行排序?
【发布时间】:2017-05-22 04:08:15
【问题描述】:

我有一个包含属性名称和出生日期(出生日期)的人员对象列表

[{'name':'robert', 'DOB':'1991-12-17'},
 {'name':'Alex', 'DOB':'1995-1-31'}, 
 {'name':'Julia','DOB':'1993-4-20'},
 {'name':'sevak', 'DOB':'1991-12-17'}, 
 {'name':'feb', 'DOB':'1991-03-07'}]

注意:DOB 仅是字符串格式。

我正在尝试根据当前日期最近即将到来的生日在 python 中对这个列表进行排序。

我的预期输出:

如果当前日期是 2017-05-21,那么输出应该如下:

[{'name':'robert', 'DOB':'1991-12-17'},
 {'name':'sevak', 'DOB':'1991-12-18'},
 {'name':'Alex', 'DOB':'1995-1-31'},
 {'name':'feb', 'DOB':'1991-03-07'},
 {'name':'Julia','DOB':'1993-4-20'}]

如果当前日期是 2017-03-14,那么输出应该如下:

[{'name':'Julia','DOB':'1993-4-20'},
 {'name':'robert', 'DOB':'1991-12-17'},
 {'name':'sevak', 'DOB':'1991-12-18'},
 {'name':'Alex', 'DOB':'1995-1-31'},
 {'name':'feb', 'DOB':'1991-03-07'}]

注意:忽略此排序的年份,我需要根据最近即将出现的生日进行排序

这是我迄今为止尝试过的:

for each_patient in patientlist: 
    globaldata.patients_records[str(each_patient['id'])] = each_patient; 
    x = each_patient['date_of_birth']; 
    if not x == None: 
    x = add_months(datetime.datetime(*[int(item) for item in x.split('-')]), 1).strftime("%Y-%m-%d"); 
    print x; 
    each_patient['date_of_birth'] = x; 
    patients.append(each_patient); 
patients_url = data['next']; 
patients.sort(key=lambda ep: ep['date_of_birth']);

在此先感谢伙计们..

【问题讨论】:

  • 向我们展示您的尝试。
  • 对于患者列表中的每个患者: globaldata.patients_records[str(each_patient['id'])] = each_patient; x = each_patient['date_of_birth'];如果不是 x == None: x = add_months(datetime.datetime(*[int(item) for item in x.split('-')]), 1).strftime("%Y-%m-%d" );打印 x;每个病人['date_of_birth'] = x;患者.附加(每个患者);患者网址=数据['下一个'];患者.sort(key=lambda ep: ep['date_of_birth']);
  • 这是一个相当不错的问题。如果你做不到,请不要投票......在整个堆栈溢出中没有人问过这样的问题。
  • 反对票源于在原始帖子中没有表现出任何努力。由于您现在已经展示了一些尝试,因此我以反对票收回。

标签: python sorting date


【解决方案1】:

您可以将这些字符串转换为datetime 对象并使用sorted() 从今天开始按日期排序:

l = [{'name': 'robert', 'DOB': '1991-12-17'},
     {'name': 'Alex', 'DOB': '1995-1-31'},
     {'name': 'Julia', 'DOB': '1993-4-20'},
     {'name': 'sevak', 'DOB': '1991-12-17'},
     {'name': 'feb', 'DOB': '1991-03-07'}]

from datetime import datetime as dt

now = dt.strptime("2017-03-14", '%Y-%m-%d')
# now=dt.now()
sorted(l, key=lambda x: (dt.strptime(str(now.year + 1) + x["DOB"][4:], '%Y-%m-%d') - now).days % 365)

结果:

[{'DOB': '1993-4-20', 'name': 'Julia'},
{'DOB': '1991-12-17', 'name': 'robert'},
{'DOB': '1991-12-17', 'name': 'sevak'},
{'DOB': '1995-1-31', 'name': 'Alex'},
{'DOB': '1991-03-07', 'name': 'feb'}]

【讨论】:

  • 非常感谢,这正是我想要的方式.. :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 2015-06-02
相关资源
最近更新 更多