python - 时间数据“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()
方法 [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
.
推荐阅读
- node.js - TypeError:无法读取未定义的属性“聊天”
- android - 如何为零经验的雇主构建移动应用程序
- spring - WebSecurityConfigurerAdapter 和 AbstractSecurityWebApplicationInitializer 不存在
- apache-spark - 如何使用 AWS ECS Fargate 而不是 EMR/EC2 运行 apache spark 作业?
- r - R的传单不显示形状文件中的多边形
- python - 如何从 SQL 转换“数据框”?
- c++ - for循环倒数到0会更快吗?
- java - 如何在 Java 程序中调用 .Net DLL 中的方法
- database - 如何在 xQuery 中找到元素的平均值?
- dart - 如何按其在飞镖中的值对地图进行排序?