Reputation: 398
I have list of UTC dates like so:
['2018-07-29T15:58:22.111904Z', '2018-07-29T15:59:22.033263Z', '2018-07-29T16:01:22.103157Z', '2018-07-30T11:41:22.032661Z', '2018-07-30T11:42:22.042215Z', '2018-07-31T12:31:21.062671Z']
This is not the full list. What I need is to grab all the dates that are found in the entire list.
So for this list:
['2018-07-29', '2018-07-30', '2018-07-31']
Would be returned.
How would this be accomplished with Python3?
Upvotes: 1
Views: 61
Reputation: 164693
You can use a set comprehension with string slicing:
L = ['2018-07-29T15:58:22.111904Z', '2018-07-29T15:59:22.033263Z',
'2018-07-29T16:01:22.103157Z', '2018-07-30T11:41:22.032661Z',
'2018-07-30T11:42:22.042215Z', '2018-07-31T12:31:21.062671Z']
res = {i[:10] for i in L}
Result:
print(res)
{'2018-07-30', '2018-07-31', '2018-07-29'}
If you need a list and do not care about order, use list(res)
.
If you need a sorted list, use sorted(res)
.
If you wish to work with datetime
objects, which is highly recommended, you should convert to datetime
and use the date
method. Here's one way with the 3rd party dateutil
module:
from dateutil import parser
res = {parser.parse(i).date() for i in L}
print(res)
{datetime.date(2018, 7, 29),
datetime.date(2018, 7, 30),
datetime.date(2018, 7, 31)}
List conversion and sorting are possible, exactly as before.
Upvotes: 3