来自ISO8601时间戳字符串的Django模型DateTimeField [英] Django model DateTimeField from an ISO8601 timestamp string

查看:140
本文介绍了来自ISO8601时间戳字符串的Django模型DateTimeField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处是Django新手。我正在为带有字符串时间戳的SQLite数据库制作Django模型,例如 2014-09-23T18:43:26.692Z 。因为我最终希望使用Django的过滤引擎进行查询(而不是使用 strftime ),所以我希望我的模型从ISO字符串生成DateTimeField对象。如果我试图在像这样的原始数据库字段上声明DateTimeField

Django newbie here. I am crafting a Django model for a SQLite database with string timestamps, e.g. 2014-09-23T18:43:26.692Z. Because I would like to eventually use Django's filtering engine for queries (instead of using strftime), I want my model to generate DateTimeField objects from ISO strings. If I try to declare a DateTimeField on the raw DB field like this

startTime = models.DateTimeField(db_column='startTime')

我收到一个错误:'unicode'对象没有属性'isoformat'

我做了一些挖掘,并尝试了以下代码:

I did some digging and tried the following code:

startTime = models.DateTimeField(dateutil.parser.parse(models.TextField(db_column='startTime'))

但是现在错误是 AttributeError:'TextField'对象没有属性'read'
我在做什么错?这甚至是正确的方法吗?

But now the error is AttributeError: 'TextField' object has no attribute 'read'. What am I doing wrong? Is this even the right approach?

推荐答案

由于没有人愿意回答这个问题,并且它出现在Google搜索的顶部,因此这里可以节省一些额外的搜索。.正如有人提到Django自己的一样dateparse模块最适合这项工作,可以将ISO8601和许多其他格式转换为Python的datetime.datetime对象,而且它支持时区,因此非常适合Django

Since nobody bothered to answer this and it showed up at the top of a Google search, here's to save some extra searching.. As someone mentioned Django's own dateparse module is best for the job and converts ISO8601 and many other formats to Python's datetime.datetime object. Also it's timezone aware and hence ideal for Django projects.

from django.utils import dateparse

x = '2014-09-23T18:43:26.692Z'
y = dateparse.parse_datetime(x)
print y

瞧!。!

2014-09-23 18:43:26.692000+00:00

这篇关于来自ISO8601时间戳字符串的Django模型DateTimeField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆