gpt4 book ai didi

python - 无法在 Django 中保存不同的日期格式

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:56 25 4
gpt4 key购买 nike

我正在处理一个表单并且有一个日期字段。我想为日期字段保存不同的日期格式,而不是使用 django。我得到“2016 年 1 月 1 日”的日期,并希望按原样保存在我的数据库中。当我尝试保存这种相同格式时会引发错误

[u"'07-Dec-2016' value has an invalid date format. It must be in YYYY-MM-DD format."].

我知道已经有人问过这种类型的问题,但它们并没有解决我的问题。

views.py

post_date = request.POST['date']

lead_obj = CustomerLeads.objects.create(posting_date = post_date)

我的模型.py

class Leads(models.Model):
customer_name = models.CharField(max_length=50,null=True, blank=True)
title = models.CharField(max_length=100, null=True, blank=True)
posting_date = models.DateField()

最佳答案

Mysql

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.

Postgresql

Date and time input is accepted in almost any reasonable format, including ISO 8601, SQL-compatible, traditional POSTGRES, and others. For some formats, ordering of day, month, and year in date input is ambiguous and there is support for specifying the expected ordering of these fields. Set the DateStyle parameter to MDY to select month-day-year interpretation, DMY to select day-month-year interpretation, or YMD to select year-month-day interpretation.

链接中的表格显示 postgresql 接受您正在寻找的格式。但是它是如何存储的呢?让我们尝试插入

INSERT INTO stackoverflow_heatwatchlist(next_date_from, next_date_to) 
VALUES('1999 Jan 05','2001 Jun 06');

当你选择时,你得到的是'2001-06-06'和'1999-01-05'

SQLite

在这里你可以以你想要的任何格式插入,它会被保存为你输入的,这是因为sqlite不强制执行任何严格的类型检查。 sqlite 中的类型纯粹是装饰性的。但 django 对此事有不同的看法,不会让你偏离标准格式太多。

SQL Server

插入数据的方式有很大的灵 active 。请参阅链接中的表格。但是它是如何存储的呢? '1999-01-05'

总结

日期在表中的存储方式完全无关紧要,重要的是接受什么格式的输入以及它如何显示。这就是 django 和 python 出色的日期和时间格式发挥作用的地方。

如果您对它们不满意,您有两种选择。第一种是将日期和时间存储为 unix 时间戳,然后自己进行所有格式化,您真正需要的只是一点数学知识 - 这是一种相当常见的做法。

第二种是使用 CharField 来存储数据,但这不是很有用。您不仅必须自己完成所有格式设置和输入验证,任何计算都将涉及大量字符串处理和转换。

关于python - 无法在 Django 中保存不同的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41178185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com