0

I have list of date from tweets on twitter which returns the time a tweet was created like these

Thu Jun 06 22:02:08 +0000 2019
Thu Jun 06 22:47:37 +0000 2019

i want to return some posts that were created 10 minutes ago

i have tried converting these to datetime and subtracting 10 minutes from current time and see if any of the above datetime fall between current time minus 10 minutes

minutes = 10
time_diff = datetime.datetime.utcnow() - datetime.timedelta(minutes=minutes)
formated_time_and_date = time_diff.strftime("%a %b %d %Y %H:%M:%S")
mins_now = int(time_diff.minute)
print(f"Minutes now: {mins_now}")
hours_now = int(time_diff.hour)

print(f"hours now: {hours_now}")
# print(formated_time_and_date[:13])
minutes = int(formated_time_and_date.split(':')[1])
recent_timeline_tweets = list(filter(lambda x: x.get(
        'date') == formated_time_and_date[:15] and
        (x.get('hours') == hours_now) and mins_now >= x.get('minutes'), tweets))

tweets variable is a list of tweets object. The idea is just to get last n minutes datetime from list of datetime, say post that are posted 10 minutes or 60 minutes ago return those datetime

Sherluck08
  • 53
  • 2
  • 9
  • It would be simpler (and it would handle tweets less than 10 minutes after midnight) if you [converted `x.get('date')` into a `datetime`](https://stackoverflow.com/q/7703865/1270789) and used that. – Ken Y-N Jun 06 '19 at 23:59

1 Answers1

1

Python 2:

import datetime
from dateutil.parser import parse

desired_minutes = 10

formated_time_and_date = [
    'Thu Jun 06 22:02:08 +0000 2019',
    'Thu Jun 06 22:47:37 +0000 2019'
]

recent_timeline_tweets = list(
    filter(
        lambda x:
            (datetime.datetime.utcnow() - parse(x).replace(tzinfo=None)) < datetime.timedelta(minutes=desired_minutes),
        formated_time_and_date
    ))

Python 3:

First install python-dateutil which was built-in in python 2:

pip install python-dateutil

Then run the above code(Which I provided for python 2) again ;)

AbdolHosein
  • 528
  • 4
  • 15
  • 1
    I was getting this error `TypeError: replace() takes no keyword arguments` what i did to fix that was convert the formated_time_and_date values to datetime like this `formated_time_and_date = [datetime.datetime.strptime( d, "%a %b %d %H:%M:%S +0000 %Y") for d in formated_time_and_date]` Your solution worked. – Sherluck08 Jun 07 '19 at 06:36
  • I've edited my solution, You need just use imported parse to solve that! `parse(x).replace(tzinfo=None)`. It's much simpler and more flexible on conversion! – AbdolHosein Jun 07 '19 at 10:41