PRAW:Python 可以打印 Reddit 评论变量但不能 return

PRAW: Python can print Reddit comment variable but not return it

我读过 this answer, a second answer and also this answer about mixing return with loops and lastly this answer 关于 return 的内容,但它们不适用于此处。

问题:我可以打印评论日期,但我似乎无法正确"return"。最后,我需要将日期添加到列表中。

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

我希望日期列表为 return

[2013-06-22 12:28:54, 2014-06-22 12:28:54, 2015-06-22 12:28:54]

但我得到的是:

[datetime.datetime(2013, 6, 22, 3, 4, 7), datetime.datetime(2013, 6, 22, 10, 33, 47)...] 

我试过的:

尝试将日期保存到循环中的变量中,但它不起作用:(我得到与上面相同的输出)

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) ...]

我该如何解决这个问题?谁能解释为什么会这样?谢谢!

上下文:如果它有任何相关性,我正在使用 praw v5.2.0 从 Reddit API.

中提取数据

如果我对你的理解正确,而你只是想存储日期时间对象的字符串表示,试试这个:

# 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

在您的原始代码中,您将 datetime.datetime 对象添加到您的列表中并返回,显然您只是在获得一个字符串列表之后,所以将您的 get_date() 调用包装在 str() 调用实现了这一点。如果您稍后仍需要在此函数之外访问 datetime 对象功能,则稍后执行此操作可能会更好。并在使用时转换为字符串。

您可以将 datatime.datatime 对象转换为字符串,将 strftime 添加到 return 句子。

datetime.datetime.fromtimestamp(time).strftime("%Y-%m-%d %H:%M:%S")