首页 > 解决方案 > 时间数据“0:02:00”与格式“%H %M %S”不匹配

问题描述

我想将字符串保存为时间格式,以将其存储在 django 项目的数据库中,这是我的utils.py文件:

import datetime
import re
import math
from django.utils.html import strip_tags

def count_words(text_string):
    word_string = strip_tags(text_string)
    matching_words = re.findall(r'\w+', word_string)
    count = len(matching_words)
    return count

def get_read_time(text_string):
    count = count_words(text_string)
    read_time_min = math.ceil(count/200.0) #Assuming 200 words per min Reading
    read_time = str(datetime.timedelta(minutes=read_time_min))
    return read_time

这是文件的必需部分models.py

class Post(models.Model):
    read_time = models.TimeField(null=True, blank=True)

这是所需的部分views.py file

class PostDetailView(DetailView):
    model = Post

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        texts = self.object.content
        # print(texts)
        read_time=get_read_time(texts)
        # print(read_time)
        Post.objects.create(read_time=datetime.strptime(read_time, "%H:%M:%S"))
        return context

字符串的输出格式是0:02:00这个我想将它作为日期时间字段保存在数据库中。但我遇到了这个错误: -


Exception Type: ValueError at /post/this-blog-contains-an-image-with-it/
Exception Value: 's' is a bad directive in format '%H:%MM:%ss'

标签: pythondjangodatetime

解决方案


TimeField[Django-doc]需要一个对象time,而不是datetime对象。您可以使用.time()方法 [Django-doc]来检索时间部分:

class PostDetailView(DetailView):
    model = Post

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        texts = self.object.content
        read_time=get_read_time(texts)
        Post.objects.create(read_time=datetime.strptime(read_time, '%H:%M:%S').time())
        return context

然而,构造一个字符串而不是返回timedelta部分本身是相当奇怪的:

def get_read_time(text_string):
    count = count_words(text_string)
    read_time_min = math.ceil(count/200.0) #Assuming 200 words per min Reading
    return datetime.timedelta(minutes=read_time_min)

然后你可以使用这个 timedelta 来获取时间:

class PostDetailView(DetailView):
    model = Post

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        texts = self.object.content
        read_time=get_read_time(texts)
        Post.objects.create(read_time=(datetime.datetime.min + read_time).time())
        return context

此外,在get_context_data. GET 请求应该没有副作用,因此您应该只对 POST、PUT、PATCH、DELETE 等请求进行数据库更改。不在get_context_data.


推荐阅读