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.

Community
  • 1
  • 1
jason
  • 3,811
  • 18
  • 92
  • 147
  • What do you mean "pull all of the dates out"? – sshashank124 Apr 27 '14 at 06: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. – savanto Apr 27 '14 at 06:56

2 Answers2

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'>]
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 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? – jason Apr 27 '14 at 06:58
  • They're called "list comprehensions", as I mentioned above. [The reference can be found in the official documentation.](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) – Makoto Apr 27 '14 at 07:00
  • 1
    This is called a list comprehension and quite a Pythonic way of solving such a problem. – Cu3PO42 Apr 27 '14 at 07:00
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.

sshashank124
  • 31,495
  • 9
  • 67
  • 76