如何解决时间数据“ 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'
解决方法
TimeField
[Django-doc]需要一个time
对象,而不是datetime
对象。您可以使用.time()
method [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,**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请求应该具有 no 副作用,因此您应该仅对POST,PUT,PATCH,DELETE等请求进行数据库更改。不在get_context_data
中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。