Reputation: 3129
I'm trying to get a list of datetime separators of a string in the same order that they occur int it.
Suppose I have the following datetime: 2015-03-25 12:22:21
; the output I intend to get from set().intersection
is a list like this: ['-', ' ']
The problem is that it comes reversed. It seems random. Take a look at the following outputs:
[IN]: list(set('/|.-T ').intersection('2015-03-25 12:22:21'))
[OUT]: [' ', '-']
Now, this one comes correct:
[IN]: list(set('/|.-T ').intersection('2015-03-25T12:22:21'))`
[OUT]: ['-', 'T']
Why does the first one comes reversed with the space first? How can I approach this to get a consistent order?
Upvotes: 2
Views: 69
Reputation: 55499
Here's a version that preserves the original order of the separators and doesn't output duplicate separators. When duplicates are present only the first one is included in the output.
def date_separators(datestring, seps):
out = []
for s in datestring:
if s in seps and s not in out:
out.append(s)
return out
# test
data = (
'2015-03-25 12:22:21',
'2015-03-25T12:22:23',
'5/6/2016 12:22:25 ',
)
seps = frozenset('/|.-T ')
for s in data:
print(s, date_separators(s, seps))
output
2015-03-25 12:22:21 ['-', ' ']
2015-03-25T12:22:23 ['-', 'T']
5/6/2016 12:22:25 ['/', ' ']
Upvotes: 2