如何从 postgresql 返回日期大于 24 小时前的行

发布于 2025-01-15 03:28:03 字数 1028 浏览 0 评论 0原文

我试图返回 postgresql 数据库中日期大于 24 小时前的所有条目。到目前为止,我所拥有的似乎只返回同一天内的日期。我相信我已将数据库时区设置为 EST,并且我认为我在查询中正确处理了它。

@router.get("/day")#, response_model=schemas.Post)
def get_post( db: Session = Depends(get_db)):
    now = datetime.now(timezone(timedelta(hours=-4), 'EST'))
    print(now)
    twenty_four_hours_ago = now - timedelta(hours=24)
    print(twenty_four_hours_ago)
    post = db.query(models.Post).filter((cast(models.Post.created_at,Date)) > twenty_four_hours_ago).all()
    #printing post above without the .first() shows teh query
    if not post:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail =f"Last post not found" )
    return post

输出似乎在 python 端输出了正确的值。

now = 2022-03-18 07:25:12.537947-04:00
twenty_four_hours_ago=2022-03-17 07:25:12.537947-04:00

但是当它与created at进行比较时,它没有找到早于2022-03-18 00:00:00-04:00的日期

created_at的格式如下。它是具有时区数据类型的时间戳。

2022-03-18 07:20:25.543046-04

希望有人能帮助我弄清楚我做错了什么。

I am trying to return all entries in my postgresql database where the date is greater than 24 hours ago. What I have so far seems to only return dates that are within the same day. I believe I have my database timezone set to EST and I thought I was dealing with it appropriately in my query.

@router.get("/day")#, response_model=schemas.Post)
def get_post( db: Session = Depends(get_db)):
    now = datetime.now(timezone(timedelta(hours=-4), 'EST'))
    print(now)
    twenty_four_hours_ago = now - timedelta(hours=24)
    print(twenty_four_hours_ago)
    post = db.query(models.Post).filter((cast(models.Post.created_at,Date)) > twenty_four_hours_ago).all()
    #printing post above without the .first() shows teh query
    if not post:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail =f"Last post not found" )
    return post

The output seems to be outputting the correct values on the python side.

now = 2022-03-18 07:25:12.537947-04:00
twenty_four_hours_ago=2022-03-17 07:25:12.537947-04:00

But when it compares to created at it does not find a date earlier than 2022-03-18 00:00:00-04:00

The format of created_at is below. It is a timestamp with timezone datatype.

2022-03-18 07:20:25.543046-04

Hoping someone can help me figure out what I am doing wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画骨成沙 2025-01-22 03:28:04

我最终将过滤器更改为以下内容并且它有效。

post = db.query(models.Post).filter(models.Post.created_at.between(twenty_four_hours_ago, now)).all()

I ended up changing the filter to the following and it works.

post = db.query(models.Post).filter(models.Post.created_at.between(twenty_four_hours_ago, now)).all()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文