Is there a way to get the time since a comment was posted using Praw?
I've looked over the docs but couldn't find any mention of it, if there isn't, are there any workarounds to get the time?
I don't know, if you're still looking for an answer. In any case, someone might find this via search engine, so here's an idea:
import praw
import datetime
reddit = praw.Reddit(...)
comment = reddit.comment(id="ctu29cb")
now = int(datetime.datetime.timestamp(datetime.datetime.today()))
then = int(comment.created)
delta = now - then
print("comment has been created with timestamp", then)
print("which means on", datetime.datetime.fromtimestamp(then).strftime('%Y-%m-%d %H:%M:%S'))
print("that was", delta, "seconds or", str(datetime.timedelta(seconds=delta)), "hours ago")
which returns
comment has been created with timestamp 1438924830
which means on 2015-08-07 05:20:30
that was 69533363 seconds or 804 days, 18:49:23 hours ago
Related
I am having issues with the python API sportsreference, I am trying to pull information for every nba matchup on a given date. I have been able to do this for ncaab, ncaaf, and nfl but am finding that the nba returns an empty dictionary.
Current code is as follows:
from sportsreference.nba import boxscore
import sportsreference
from datetime import datetime
now = datetime.now()
box_scores_nba = sportsreference.nba.boxscore.Boxscores(now)
print(box_scores_nba.games)
Output is:
{'12-26-2020': []}
Does anyone have any idea why I am not pulling any info when there are games scheduled this day? I have been trying to read the documentation for sportsreference and am getting nowhere.
Thanks -
Edited based on Comments
The BoxScore() method only gives a value for the previous day and does not give any detail for today/upcoming days, this is because the website itself does not provide these details! check here.
On the other hand you can get the schedule of a particular team using this code:
from sportsreference.nba.schedule import Schedule
houston_schedule = Schedule('HOU')
for game in houston_schedule:
print(game.date) # Prints the date the game was played
print(game.result) # Prints whether the team won or lost
Even then there are incorrect output I receive in the dataset!
Like the result of the upcoming games are shown as 'win'.
In my opinion, it is better to avoid this API and go for better websites and use webscraping (unless you don't want real-time data) as I find these results very raw, confusing and misleading here and there!
I am trying to figure out a clever way to take a user's input and store it in a database to be retrieved at a later date.
For context, this is a Discord bot where I am trying to track users' schedules. The idea is that the user could say "&addtime 12/30/1 12pm CST" and the bot would record that they will be online at 12/30/1/ at 12pm CST
The reason I want to track the timezone is so I can convert all the timezones to a specific timezone so that timezones wont get confused.
So after someone adds their time above, if I (someone PST), goes to retrieve when people will be online, I can type "&schedules PST" and get all of the times in the specified timezone.
The problem I'm facing now is all of the datetime examples I can find online all take very exact and specific input. I'm looking for a more forgiving function that is smart enough to figure out datetimes.
Figured it out with this method. it only supports US timezones, but that was enough for my needs:
from dateutil import parser
from dateutil import tz
import pytz
def parse_date(self, msg):
ET = tz.gettz('US/Eastern')
CT = tz.gettz('US/Central')
MT = tz.gettz('US/Mountain')
PT = tz.gettz('US/Pacific')
us_tzinfos = {'CST': CT, 'CDT': CT,
'EST': ET, 'EDT': ET,
'MST': MT, 'MDT': MT,
'PST': PT, 'PDT': PT}
usertime = parser.parse(msg, tzinfos=us_tzinfos)
servertime = usertime.astimezone(pytz.timezone("America/Phoenix"))
parse_date("12/30/20 12pm EST")
I am building a scraper that searches reddit comments for keywords. I am having two problems
Problem 1. in order to build the commentforest I need to get the submission_id from the comment so I can pull all of the comments related to that submission.I am having trouble figuring out how to get the submission id.
problem 2. for some reason every time I run this code it gives me new comments that include the keywords (I am assuming this is just because new comments have been added) BUT some of the old comments arent showing up when i run the code again. this is supposed to pull ALL the comments that match my keyword from the subreddit what am i doing wrong?
from psaw import PushshiftAPI
from datetime import datetime, timezone, timedelta
from dateutil.relativedelta import relativedelta
api = PushshiftAPI()
comments = api.search_comments(q='OP', subreddit='askreddit')
max_response_cache = 1000
cache = []
commentcount = 0
for c in comments:
cache.append(c)
commentcount += 1
print (f' comment {commentcount}: {c.body}')
I want the code to print out the submission id related to the comments and I want to be able to pull all the comments that match my keywords.
I am looking to build a web application that utilizes the Reddit (open source) algorithm.
I plan to tweak it over time but for now I think it'll be a good start to use their ranking system.
I read a blog post about this algorithm and the example is written in Python. How can I convert this for use in ColdFusion? Additional bonus points for usage in a CFC if it's easier?
The code:
#Rewritten code from /r2/r2/lib/db/_sorts.pyx
from datetime import datetime, timedelta
from math import log
epoch = datetime(1970, 1, 1)
def epoch_seconds(date):
"""Returns the number of seconds from the epoch to date."""
td = date - epoch
return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
def score(ups, downs):
return ups - downs
def hot(ups, downs, date):
"""The hot formula. Should match the equivalent function in postgres."""
s = score(ups, downs)
order = log(max(abs(s), 1), 10)
sign = 1 if s > 0 else -1 if s < 0 else 0
seconds = epoch_seconds(date) - 1134028003
return round(order + sign * seconds / 45000, 7)
The blog post that talks about this code:
http://amix.dk/blog/post/19588
Looking forward to hearing some ideas and examples.
Many thanks!
Michael.
Also, as an additional question; would this code be better performed via an SQL query or some kind of sorting in ColdFusion after the data-set has already been collected? My DB of choice would be MySQL.
UPDATE:
Just found another question on here that relates to what I was asking...I think it helps.
How are Reddit and Hacker News ranking algorithms used?
Most of that code is just standard code from any programming language
For example to get the seconds since a certain date is pretty easy in ColdFusion
<cfset seconds = dateDiff('s', now(), createDate(1970, 1, 1)) />
Not sure which bits your stuck with, but its all prety simple. Every function I see there has a ColdFusion version and without just wanting someone to rewrite it for you, I suggest you try to do it and ask if you get stuck with something.
I have an action that a user can do many times a day. I'm trying to get a count of how many times the user has taken that action, but only for today's date. Here's the way I'm currently solving this, but is there an easier way? I feel like I should be able to fit this in one line. :)
today_slaps = 0
slaps = Slap.objects.filter(from_user=request.user.id)
for slap in slaps:
if slap.date.date() == datetime.now().date():
today_slaps += 1
The logic I'm looking for is:
slaps = Slap.objects.filter(from_user=2, date.date()=datetime.now().date()).count()
But that's obviously throwing an error that a keyword can't be an expression. Sorry if this is a basic one, but thoughts?
slap_count = Slap.objects.filter(from_user=request.user, \
date__gte=datetime.date.today()).count()
# specifically setting datetimefield=datetime.date.today() won't work
# gte = will work for datetimefield vs datetime object starting at that date
# it's also assumed there will never be a slap from the future.
Generates the following SQL:
SELECT ... FROM ... WHERE ... date >= 2011-02-26 00:00:00
So it's safe to say you will only get today's slaps, again, unless you have slaps from the future. If you do, I'd set every date__day, date__year, date__month explicitly.
Thanks to Yuji (below) we came up with this answer:
slap_count = Slap.objects.filter(from_user=request.user.id, date__gte=datetime.today().date()).count()