如何使用日期时间对字符串日期进行排序,以及如何使用flaskapp查看视图?

时间:2019-03-19 16:26:02

标签: mongodb datetime flask datetime-format

我有一个Flask网络应用程序,该应用程序使用PRAW收集reddit提交并存储到MongoDB集合中,当涉及到查看集合时,我想首先按最近的提交日期查看,目前该集合未在查看以任何顺序?

这是我用来填充MongoDB集合的脚本:

#! usr/bin/env python3
# data_ingestion.py    

import praw
from pymongo import MongoClient
import json
from datetime import datetime
import logging

# setting your local MongoDB instance to a var called MONGO_HOST
MONGO_HOST = 'mongodb://localhost:27017/gm_sandbox'
client = MongoClient(MONGO_HOST)
db = client.gm_sandbox

# setting up PRAW OAuth
reddit = praw.Reddit(client_id='id',\
                 client_secret='client_server',\
                 user_agent='reddit-top-posts',\
                 username='username',\
                 password='password'


# flushing collection before inserting new documents
db.top_reddit_posts.drop()

# filtering PRAW by subreddit
subreddit = reddit.subreddit('datascience').top('week')

# creating document:
for post in subreddit:

    utc_date = post.created_utc
    parsed_date = datetime.utcfromtimestamp(utc_date)

    data = {
        'title': post.title,
        'date': utc_date,
        'date_str': parsed_date.strftime('%Y-%m-%d'),
        'score': post.score,
        'url': post.url,
        'sub': str(post.subreddit),
        'commentsUrl': post.url
        #'author': str(post.author)

    }
    # inserting documents into MongoDB collection.
    db.top_reddit_posts.insert_one(data)

这是我用来显示和订购收藏的功能:

def all_dates():
dates = posts_get_distinct_items('date_str')

return render_template(
    'all-dates.html',
    dates=reversed(dates) # latest date on top
    )

应用程序正在显示每个Reddit提交的日期列表,但这些日期未排序且处于随机位置?

unsorted submission dates

0 个答案:

没有答案