Leb
Leb

Reputation: 15953

Filter rows based on date

I have a set of data that resembles this format:

id,timestamp,pid
[(1231, '2015-08-31 15:21:15', 1546),
 (3451, '2015-09-01 15:21:15', 4984),
 (4561, '2015-09-01 15:21:15', 6464),
 (5671, '2015-09-02 15:21:15', 5484)]

I'm trying to extract the rows that contain the date "2015-09-01". I thought about applying a map, but it works on the row as a whole if I understood it correctly.

So I tried another alternative by attempting

datetime.strptime(df.timestamp, "%Y-%m-%d %H:%M:%S")

but got this:

TypeError: must be str, not method

Ultimately I thought of extracting the rows that match this condition:

datetime.strptime("2015-08-30 23:59:59", "%Y-%m-%d %H:%M:%S") > 
               datetime.strptime(df.timestamp, "%Y-%m-%d %H:%M:%S") >
               datetime.strptime("2015-09-02 00:00:00", "%Y-%m-%d %H:%M:%S")

My question

What would be a more proper way to implement that method, or is there another alternative?

Upvotes: 0

Views: 235

Answers (1)

the
the

Reputation: 21949

You probably want to use filter. Since all dates are formatted using - this works fine:

filter(lambda x: '2015-09-01' in x[1], the_list)

Which results in:

[(3451, '2015-09-01 15:21:15', 4984), (4561, '2015-09-01 15:21:15', 6464)]

You can also do stuff like:

filter(lambda x: '2015-09-01' < x[1], the_list)

Which gives:

[(3451, '2015-09-01 15:21:15', 4984), 
 (4561, '2015-09-01 15:21:15', 6464),  
 (5671, '2015-09-02 15:21:15', 5484)]

Upvotes: 1

Related Questions