如何从 postgresql 返回日期大于 24 小时前的行
我试图返回 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最终将过滤器更改为以下内容并且它有效。
I ended up changing the filter to the following and it works.