Python:从日期时间列表创建对人类友好的字符串 [英] Python: create human-friendly string from a list of datetimes

查看:105
本文介绍了Python:从日期时间列表创建对人类友好的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上正在寻找与此问题相反的东西:
将字符串转换为日期时间

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

我有一个日期时间对象列表,我想从其中创建一个对人类友好的字符串
,例如 Jan 27 and 30, 2012年2月4日。有什么想法吗?

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?

请注意,strftime仅适用于单个datetime对象。这里的问题是您有一个日期时间列表,这些日期时间可能不是均匀间隔的,可能跨越月或年边界,但是整个日期范围必须用一个简洁的字符串表示。

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.

推荐答案

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]

或者使用for循环:

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

UPDATE 2 :我相信这更接近您的期望,但是仍然是您想要的,只有您知道:您想何时显示年份,何时不显示?何时只显示月份或日期,等等。。。但这基本上是一个主意。您可能需要做一个类来表示范围,您可以在那里选择格式,比较范围之间的月份和年份,...这就是我现在想的。希望对您有所帮助。

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

这篇关于Python:从日期时间列表创建对人类友好的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆