Python: create human-friendly string from a list o

2020-06-30 05:31发布

I'm actually looking for the opposite of this question: Converting string into datetime

I have a list of datetime objects and I want to create a human-friendly string from them, e.g., "Jan 27 and 30, Feb 4, 2012". Any ideas?

Note that strftime only works on a single datetime object. The problem here is that you have a list of datetimes that might not be evenly spaced, might cross month or year boundaries, but the entire range of dates has to be expressed in a single, concise string.

2条回答
疯言疯语
2楼-- · 2020-06-30 06:10

This.

your_date.isoformat() # -> '2002-03-11'
your_date.strftime("%A %d. %B %Y") # -> Monday 11. March 2002

UPDATE: You need list comprehension to do it in one line.

date_strings = [dt.strftime("%A %d. %B %Y") for dt in your_date_list]

Or, use a for loop:

date_strings = []
for dt in your_date_list:
    date_str.append(dt.strftime("%A %d. %B %Y"))

UPDATE 2: This I believe is closer to what you expect, but still what you want, only you knows it: when do you want to show the year, when not? when to show the month or the day only, etc... But this is basically an idea. You'll have maybe to do some kind of a class to represent the ranges, where you could choose the format there, comparing months and years between the ranges, ... That's what I came up with now. Hope it helps:

import datetime

# sample input
dates = [datetime.date(2012, 5, 21), datetime.date(2012, 5, 23),
        datetime.date(2012, 5, 25), datetime.date(2012, 5, 19),
        datetime.date(2012, 5, 17), datetime.date(2012, 5, 26),
        datetime.date(2012, 5, 18), datetime.date(2012, 5, 20)]

def get_consecutive_ranges(dates):
    dates = sorted(dates)

    delta_1day = datetime.timedelta(days=1)
    ranges = []
    last_d = dates[0]
    tmp_range = [last_d, None]
    for d in dates[1:]:
        if d-last_d <= delta_1day:
            # the difference between the dates is less than a day
            # we can extend the range, update the right-most boundary
            tmp_range[1] = d
        else:
            ranges.append(tmp_range)
            tmp_range = [d, None]
        last_d = d
    else:
        ranges.append(tmp_range)
    return ranges

ranges = get_consecutive_ranges(dates)

fmt = "%d %b %Y"

output = ", ".join([("%s" % (r[0].strftime(fmt),)) if r[1] is None else \
            ("%s-%s" % (r[0].strftime(fmt), r[1].strftime(fmt))) \
            for r in ranges])

print output
查看更多
狗以群分
3楼-- · 2020-06-30 06:19
>>> dt=datetime.date(2012,2,4)
>>> dt.strftime('%A %B %d, %Y')
'Saturday February 04, 2012'
查看更多
登录 后发表回答