Limit RSS feeds by date using feedparser. [Python]

I am repeating the RSS feed so where _file is the feed

d = feedparser.parse(_file)
for element in d.entries: 
    print repr(element.date)

The date output is obtained in this way

u'Thu, 16 Jul 2009 15:18:22 EDT'

It seems I don’t understand how to actually quantify the output above, so I can use it to limit the elements of the feed. I am asking how I can get the actual time from this, so I can say, if more than 7 days, skip this element.

+3
source share
3 answers

feedparser should provide you with a struct_time object from the Python time module. I assume that it does not recognize the date format and therefore gives you a raw string.

See here how to add support for parsing invalid timestamps:

http://pythonhosted.org/feedparser/date-parsing.html

struct_time, :

http://docs.python.org/library/time.html#time.struct_time

struct_time , . :

time.struct_time(tm_year=2010, tm_mon=2, tm_mday=4, tm_hour=23, tm_min=44, tm_sec=19, tm_wday=3, tm_yday=35, tm_isdst=0)

structs , :

import time
import calendar

struct = time.localtime()
seconds = calendar.timegm(struct)

, , , datetime timedeltas.

+5

>>> import time
>>> t=time.strptime("Thu, 16 Jul 2009 15:18:22 EDT","%a, %d %b %Y %H:%M:%S %Z")
>>> sevendays=86400*7
>>> current=time.strftime ("%s",time.localtime())
>>> if int(current) - time.mktime(t) > sevendays:
        print "more than 7 days"

datetime timedelta() .

+1

If you install the dateutil module :

import dateutil.parser as dp
import dateutil.tz as dtz
import datetime

date_string=u'Thu, 16 Jul 2009 15:18:22 EDT'
adatetime=dp.parse(date_string)
print(adatetime) 
# 2009-07-16 15:18:22-04:00

now=datetime.datetime.now(dtz.tzlocal())
print(now)
# 2010-02-04 23:35:52.428766-05:00

aweekago=now-datetime.timedelta(days=7)
print(aweekago)
# 2010-01-28 23:35:52.428766-05:00

if adatetime<aweekago:
    print('old news')

If you use Ubuntu, dateutilprovided by the package python-dateutil.

0
source

Source: https://habr.com/ru/post/1731495/


All Articles