python - 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
解决方案
蟒蛇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提供的);)
推荐阅读
- r - 计算每个字符并存储为
一对 - c# - StringFormat 在 Designer 中显示错误,但在编译后不显示
- docker - Boot2docker 与詹金斯
- ios - 如何在 Swift3 iOS 中的 Video AVAsset 上添加淡入淡出效果
- angular - 如何将 Angular Material 多选项目限制为 N 个项目?
- c# - 运算符 '&&' 不能应用于 bool 和 bool 的操作数?
- ios - UISEGMENTED CONTROL ui修改
- apache - Apache 2.4.25 一些标头在代理请求中被剥离
- angular - Ngrx Store:执行某些操作后,有什么方法可以获取状态差异
- r - 加载一个 .RData 生成一个大函数而不是数据框