Python: create human-friendly string from a list of datetimes

2024/11/17 13:35:25

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.

Answer

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 boundarytmp_range[1] = delse:ranges.append(tmp_range)tmp_range = [d, None]last_d = delse:ranges.append(tmp_range)return rangesranges = 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
https://en.xdnf.cn/q/118794.html

Related Q&A

Python replace non digit character in a dataframe [duplicate]

This question already has answers here:Removing non numeric characters from a string in Python(9 answers)Closed 5 years ago.I have the following dataframe column>>> df2[Age]1 25 2 35 3 …

PyGame.error in ubuntu

I have problem with pygame and python 3 in ubuntu 12.10. When i tried load an image i got this error: pygame.error: File is not a Windows BMP fileBut in python 2.7 all works fine. I use code from http:…

Firebase Admin SDK with Flask throws error No module named firebase_admin

--- Question closedIt was my mistake, my uWSGI startup script switches to a different virtualenv.--- Original questionIm trying to publish push notifications from my Flask app server to Android APP. Se…

Recursive generator for change money - python

First, thanks for any help. I have this recursive code for counting ways of change from a list of coins and a given amount. I need to write a recursive generator code that presents the ways in every it…

Like button not recording the data [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Python, Pygame, Image manipulation: Restretch a loaded png, to be the texture for an isometric Tile

Im a 17 year old programmer, trying to program an isometric game in python, with pygame. After finishing a tile engine, working with not good looking, gimp-drawn PNGs, I wondered, if it would be possib…

TypeError: list object is not callable [duplicate]

This question already has answers here:TypeError: list object is not callable while trying to access a list(9 answers)Closed 10 years ago.I cant find the problem im facing... this is exactly what the …

Tokenise text and create more rows for each row in dataframe

I want to do this with python and pandas.Lets suppose that I have the following:file_id text 1 I am the first document. I am a nice document. 2 I am the second document. I am an even …

Is the example of the descriptor protocol in the Python 3.6 documentation incorrect?

I am new to Python and looking through its documentation I encountered the following example of the descriptor protocol that in my opinion is incorrect. .It looks like class IntField:def __get__(self, …

How to clean a string to get value_counts for words of interest by date?

I have the following data generated from a groupby(Datetime) and value_counts()Datetime 0 01/01/2020 Paul 803 2 01/02/2020 Paul 210982360967 1 …