Django处理带T、带Z的时间格式
问题:
USE_TZ = False后,django orm 查询时间报错:MySQL backend does not support timezone-aware datetimes when USE_TZ is False.
解决: 查询时间前,做替换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import pytz from django.utils import timezone USE_TZ = False if USE_TZ is True : tzinfo_ = pytz.utc else : tzinfo_ = None start_time_str = '2019-11-01T16:00:00.000Z' end_time_str = '2019-11-02T16:00:00.000Z' # 时间做时区转换 start_time = timezone.datetime.strptime(start_time_str, '%Y-%m-%dT%H:%M:%S.%fZ' ).replace(tzinfo = tzinfo_) end_time = timezone.datetime.strptime(end_time_str, '%Y-%m-%dT%H:%M:%S.%fZ' ).replace( tzinfo = tzinfo_) # 查询mysql数据库 query_set = TestModel.objects. filter (create_time__range = (start_time, end_time)) |
但出来后的时间会定位到16:00,少8小时,具体处理实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | def get_queryset( self ): start = self .request.query_params.get( 'daterangeStart' , None ) stop = self .request.query_params.get( 'daterangeEnd' , None ) if start and stop: print ( "---------过滤时间-----------" ) print ( type (start), type (stop)) print (start, stop) tzinfo_ = None # 时间做时区转换 start = timezone.datetime.strptime(start, '%Y-%m-%dT%H:%M:%S.%fZ' ).replace(tzinfo = tzinfo_) stop = timezone.datetime.strptime(stop, '%Y-%m-%dT%H:%M:%S.%fZ' ).replace(tzinfo = tzinfo_) # query_set = TestModel.objects.filter(create_time__range=(start_time, end_time)) print (start, stop) start = time.strptime( str (start), '%Y-%m-%d %H:%M:%S' ) start = time.mktime(start) # start11 = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()+28800)) start = time.strftime( "%Y-%m-%d %H:%M:%S" , time.localtime(start + 28800 )) stop = time.strptime( str (stop), '%Y-%m-%d %H:%M:%S' ) stop = time.mktime(stop) stop = time.strftime( "%Y-%m-%d %H:%M:%S" , time.localtime(stop + 28800 )) print (start, stop) return DataPointUserActionDetaTextModel.objects. filter (create_datetime__gte = start). filter (create_datetime__lte = stop) return DataPointUserActionDetaTextModel.objects. all () |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 三行代码完成国际化适配,妙~啊~
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?