[英]Django: Trunc datetime results in none
I have the following model: 我有以下型号:
class Statistic(models.Model):
meter = models.ForeignKey(Meter, on_delete=models.CASCADE, db_index=True)
timestamp_start = models.DateTimeField(db_index=True)
timestamp_end = models.DateTimeField(db_index=True)
usage_start = models.DecimalField(max_digits=10, decimal_places=3)
usage_end = models.DecimalField(max_digits=10, decimal_places=3)
return_start = models.DecimalField(max_digits=10, decimal_places=3)
return_end = models.DecimalField(max_digits=10, decimal_places=3)
I have the following value in the first record of timestamp_start in my sqllite database 我在sqllite数据库中的timestamp_start的第一条记录中有以下值
2016-12-22T06:15:30.420+02:00
When I run the following query: 当我运行以下查询时:
statistics = Statistic.objects.filter(id=1)
.annotate(timestamp=Trunc('timestamp_start','day', output_field=DateTimeField()))
.values('timestamp')
.annotate(usage_start = Min('usage_start'))
timestamp results in None 时间戳结果为无
QuerySet [{'usage_start': Decimal('136.972'), 'timestamp': None}] QuerySet [{'usage_start':十进制('136.972'),'时间戳':无}]
When I attach the debugger and check the first records of my statistics table like this 当我附加调试器并检查我的统计表的第一个记录时,如下所示
Statistics.objects.all()[0].timestamp_start
it returns: 它返回:
datetime.datetime(2016, 12, 22, 6, 0) datetime.datetime(2016,12,22,6,0)
Before facing this problem I got this exception: 在遇到这个问题之前我得到了这个例外:
Database returned an invalid datetime value. 数据库返回了无效的日期时间值。 Are time zone definitions for your database and pytz installed? 是否安装了数据库和pytz的时区定义?
I do have pytz installed. 我确实安装了pytz。 But no idea how to fix this. 但不知道如何解决这个问题。 Is the value incorrect ? 价值不正确吗? Anyway in the end I set use_tz in settings.py to false. 无论如何,最后我将settings.py中的use_tz设置为false。 The exception vanisched but trunc returns none now. vanisched异常但trunc现在没有返回。 Is this causing the problem? 这会导致问题吗?
ps: My environment Python 3, Django, Sql lite database, windows ps:我的环境Python 3,Django,Sql lite数据库,windows
You probably haven't loaded the timezone data into mysql. 您可能尚未将时区数据加载到mysql中。 TruncDate uses the CONVERT_TZ
function under the hood, which returns NULL
if no timezone data is available. TruncDate使用引擎盖下的CONVERT_TZ
函数,如果没有可用的时区数据,则返回NULL
。 You can check what SQL the query is using by evaluating the following: 您可以通过评估以下内容来检查查询使用的SQL:
str(statistics.query)
Windows instructions for loading timezone data can be found here: 有关加载时区数据的Windows说明,请访问:
I ran into this issue on Linux and resolved it as indicated in this other StackOverflow post: 我在Linux上遇到了这个问题,并按照其他StackOverflow帖子的说明解决了这个问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.