首页 > 解决方案 > How to subtract n minutes from list of datetime and return the datetime that matches

问题描述

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

标签: pythonpython-3.xdatetimetwitter

解决方案


蟒蛇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
    ))

蟒蛇 3:

第一次安装python-dateutil在 python 2 中内置:

pip install python-dateutil

然后再次运行上面的代码(我为python 2提供的);)


推荐阅读