0
import datetime a=[datetime.datetime(2014, 4, 13, 0, 0), u'a', u'b', u'c',datetime.datetime(2014, 4, 14, 0, 0), u'a', u'b', u'c', datetime.datetime(2014, 4, 15, 0, 0), u'a', u'b', u'c'] 

How do I pull all of the dates out of this list?

I can always loop through and test. But how do I do it better?

I can use regex, like I did here python regular expression, pulling all letters out. But I know there are much more efficient ways.

I looked through here https://docs.python.org/2/library/stdtypes.html but it doesn't seem like the datetime object is a built-in type. So I guess I can't go that route. Other suggestions please.

note: I don't know if the date will be every 4th value. I need something irregardless of pattern.

2
  • What do you mean "pull all of the dates out"? Commented Apr 27, 2014 at 6:49
  • Any regex or other matching procedure you use will necessarily loop through the list one way or another anyway. You might as well do it yourself. See Makoto's answer. Commented Apr 27, 2014 at 6:56

2 Answers 2

4

We know that the type that you want is datetime.datetime, so writing a list comprehension seems to be the cleanest way to do it (without worrying about a pattern):

b = [i for i in a if type(i) == datetime.datetime] 

I doubt you could use regex for this (unless you converted everything to a string), unless you elected to convert every datetime to a string or unicode representation, and at that point, you're checking the type anyway...

>>> print [type(i) for i in a] [<type 'datetime.datetime'>, <type 'unicode'>, <type 'unicode'>, <type 'unicode'>, <type 'datetime.datetime'>, <type 'unicode'>, <type 'unicode'>, <type 'unicode'>, <type 'datetime.datetime'>, <type 'unicode'>, <type 'unicode'>, <type 'unicode'>] 
Sign up to request clarification or add additional context in comments.

3 Comments

thanks Makoto. Can you point to where I can read more about putting a for and if statement in the same line? what is that called?
They're called "list comprehensions", as I mentioned above. The reference can be found in the official documentation.
This is called a list comprehension and quite a Pythonic way of solving such a problem.
0

Look at your code, your list seems to be as follows:

a = [date, x, x, x, date, x, x, x, date, x, ...] 

For that you can do:

b = a[::4] 

and then get each datetime object formatted to whatever pattern you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.