将datetime字符串解析为Django DateTimeField [英] Parsing a Datetime String into a Django DateTimeField

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

问题描述

我有一个包含一个类型为DateTimeField的模型的Django应用程序。

我从网络上以的形式提取数据2008-04-10 11: 47:58-05

我相信这个例子中的最后3个字符是时区。

如何保留DateTimeField中的数据两者之间有简单的转换吗?将DateTimeField设置为仅包含上述格式的字符串会抛出ValidationError。



谢谢!

解决方案

您可以使用

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

哪个返回一个datetime(可以分配给DateTimeField)。


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.

Thank you!

解决方案

You can use

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

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

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

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