繁体   English   中英

在我的代码中,为什么我的列表没有从最早到最晚的日期排序? 有人可以帮我解决这个问题吗?

[英]In my code, why doesn't my list sort from the earliest to the latest in dates? Can someone please help me solve this problem?

from datetime import date, timedelta, time, datetime

# 1 Complete read_date()
def read_date(date_object):
    """Read a string representing a date in the format 2121-04-12, create a
    date object from the input string, and return the date object
    """
    dt_string = '2121-04-12'
    date_object = datetime.strptime(date_object, '%Y-%m-%d').date()
    return date_object
# 2. Use read_date() to read four (unique) date objects, putting the date objects in a list
date1 = input()
date2 = input()
date3 = input()
date4 = input()

date1_read = read_date(date1)
date2_read = read_date(date2)
date3_read = read_date(date3)
date4_read = read_date(date4)

list_date = []
list_date.append([date1, date2, date3, date4])
split_list = 

# 3. Use sorted() to sort the dates, earliest first
list_sorted = sorted(list_date)
print(list_sorted)
# 4. Output the sorted_dates in order, earliest first, in the format mm/dd/yy
new_format = 
# 5. Output the number of days between the last two dates in the sorted list
#    as a positive number

# 6. Output the date that is 3 weeks from the most recent date in the list

# 7. Output the full name of the day of the week of the earliest day

在 #3 下,我需要以特定格式对最早的日期进行排序。 我需要帮助对列表进行排序,因为我的代码没有对其进行排序。 我还需要帮助以特定方式格式化整个列表。

也许这就是你要找的东西? 试试看你有没有问题。

确认这是正确的排序顺序后,您可以轻松地每个元组连接到一个日期字符串中。 --- 作为你的练习离开。

>>>list_date = '2022-01-27,2022-07-04,2020-12-31,2022-07-29'  # your inputs
>>>tuple_date = []
>>>for d in list_date.split(','):        # separate to each date
       yy, mm, day = d.split('-')        # sep. to 3 parts by hyphen 
       tuple_date.append((yy,mm, day))   # glue them into one unit

    
>>>tuple_date
[('2022', '01', '27'), ('2022', '07', '04'), ('2020', '12', '31'), ('2022', '07', '29')]
>>>sorted(tuple_date)                    # use sorted by each tuple.
[('2020', '12', '31'), ('2022', '01', '27'), ('2022', '07', '04'), ('2022', '07', '29')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM