将日期时间字符串解析为 Django DateTimeField [英] Parsing a Datetime String into a Django DateTimeField

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

问题描述

我有一个 Django 应用程序,其模型包含 DateTimeField 类型的字段.
我正在以 2008-04-10 11:47:58-05 的格式从网上提取数据.
我相信这个例子中的最后 3 个字符是时区.
如何在 DateTimeField 中保留该数据,两者之间是否可以轻松转换?将 DateTimeField 设置为仅包含上述格式的字符串会引发 ValidationError.

I have a Django app with a model that contains a field of type DateTimeField.
I am pulling data from the web in the format of 2008-04-10 11:47:58-05.
I believe that the last 3 characters in this example are the timezone.
How can I preserve that data in the DateTimeField, and is there an easy conversion between the two? Setting the DateTimeField to simply contain a string of the above format throws a ValidationError.

谢谢!

推荐答案

可以用

import dateutil.parser
dateutil.parser.parse('2008-04-10 11:47:58-05')

它返回一个日期时间(可以分配给 DateTimeField).

Which returns a datetime (that can be assigned to the DateTimeField).

这篇关于将日期时间字符串解析为 Django DateTimeField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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