如何通过将正常日期和日期时间与时区进行比较来过滤数据?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过将正常日期和日期时间与时区进行比较来过滤数据?相关的知识,希望对你有一定的参考价值。
我有一些数据存储在数据库中,我正在通过flask和flask-sqlalchemy访问和过滤。
我正在尝试根据start
和end
日期过滤数据,这些数据将被用作URL中request.args.get()
的用户输入。在数据库中,数据为"2020-05-12T00:00:00+02:00"
格式,当用户输入日期时,他将只输入日期而不是时间或时区(例如:2020-05-12
)。因此,基于用户为start
和end
(包括end
)输入的值,我想比较日期并返回这些值。但是,返回值必须具有原始日期格式
数据如下:
{
"items": [
{
"id": 1,
"value": 21.4,
"start": "2020-05-12T00:00:00+02:00",
"end": "2020-05-12T01:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 2,
"value": 18.93,
"start": "2020-05-12T01:00:00+02:00",
"end": "2020-05-12T02:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 3,
"value": 18.06,
"start": "2020-05-13T02:00:00+02:00",
"end": "2020-05-13T03:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 4,
"value": 17.05,
"start": "2020-05-13T03:00:00+02:00",
"end": "2020-05-13T04:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 5,
"value": 16.84,
"start": "2020-05-14T04:00:00+02:00",
"end": "2020-05-14T05:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 6,
"value": 19.3,
"start": "2020-05-14T05:00:00+02:00",
"end": "2020-05-14T06:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
}]}
示例:
如果:
[start
是2020-05-12
&end
是2020-05-14
,根据以上数据,必须返回以下数据:
{
"items": [
{
"id": 1,
"value": 21.4,
"start": "2020-05-12T00:00:00+02:00",
"end": "2020-05-12T01:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 2,
"value": 18.93,
"start": "2020-05-12T01:00:00+02:00",
"end": "2020-05-12T02:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 3,
"value": 18.06,
"start": "2020-05-13T02:00:00+02:00",
"end": "2020-05-13T03:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 4,
"value": 17.05,
"start": "2020-05-13T03:00:00+02:00",
"end": "2020-05-13T04:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 5,
"value": 16.84,
"start": "2020-05-14T04:00:00+02:00",
"end": "2020-05-14T05:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
}]}
答案
如果您从request.args.get()
中获取值,如下所示:
start_date = request.args.get('start')
end_date = request.args.get('end')
然后您可以使用dateutil.parser.parse将日期解析为isoformat(),然后对其进行过滤:
start_date = dateutil.parser.parse(filters['start']).isoformat()
end_date = dateutil.parser.parse(filters['end']).isoformat()
items = YourModel.query.filter(YourModel.start >= start_date).filter(YourModel.end <= end_date)
以上是关于如何通过将正常日期和日期时间与时区进行比较来过滤数据?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 C# 应用程序范围内更改仅日期部分将用于日期时间比较