I've read this answer, a second answer and also this answer about mixing return with loops and lastly this answer about returns, but they don't apply here.
Problem: I can print the date of comment, but I can't seem to "return" it properly. Ultimately, I need to add the dates to a list.
import datetime
def get_date(submission):
time = submission.created
return datetime.datetime.fromtimestamp(time)
authors_list = []
date_list = []
# Problem is here:
for comment in submission.comments.list():
authors_list.append(comment.author) # works fine!
date_list.append(get_date(comment)) # does not work
print authors_list
print date_list # does not work
I expect the date list to return
[2013-06-22 12:28:54, 2014-06-22 12:28:54, 2015-06-22 12:28:54]
But instead I get:
[datetime.datetime(2013, 6, 22, 3, 4, 7), datetime.datetime(2013, 6, 22, 10, 33, 47)...]
What I've tried:
Tried saving the date to a variable within the loop, but it doesn't work: (I get the same output as above)
date_list = [ ]
for comment in submission.comments.list():
a_date = get_date(comment)
date_list.append(a_date)
print date_list
>>> [datetime.datetime(2013, 6, 22, 3, 4, 7) ...]
How do I fix this? And can anyone explain why this happens? Thanks!
Context: If its of any relevance, I'm using praw
v5.2.0 to extract data from the Reddit API.
If I understand you correctly, and you just want to store the string representation of the datetime object try this:
# Problem is here:
for comment in submission.comments.list():
authors_list.append(comment.author) # works fine!
date_list.append(str(get_date(comment))) # should now work as expected
In your original code you added the datetime.datetime
object you your list and returned the, apparently you are after just having a list of strings, so wrapping you get_date()
call in a str()
call achieves this. although it may be better to do this later if you still need access to the datetime
object functionality later, outside of this function. and convert to string at the point of use.