Python 从 Django DateTimeField 获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35300460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:15:03  来源:igfitidea点击:

Get date from a Django DateTimeField

pythondjango

提问by Juan Carlos Asuncion

I would like to request some assistance regarding this matter

我想就此事请求一些帮助

I am learning django and trying out some codes but I hit a brick wall at trying to get the date only from a model's DateTimeField

我正在学习 django 并尝试一些代码,但我在尝试仅从模型的 DateTimeField 中获取日期时遇到了困难

here's the code that I am working on:

这是我正在处理的代码:

class APPLICANT_DATA(models.Model):
    SCHEDULED_AT = models.DateTimeField(null=True, blank=True)


def somefunction():
    app_data = APPLICANT_DATA.objects.all()
    for item in app_data:
        the_date = str(item.SCHEDULED_AT.strftime("%B-%d-%Y")) + ", " + the _date

And I am getting ('NoneType' object has no attribute 'strftime') even though my model contains 3 records that all have date and time

'NoneType' object has no attribute 'strftime'即使我的模型包含 3 个都有日期和时间的记录,我也得到了 ( )

What am I doing wrong? any advice for a newbie? many thanks.

我究竟做错了什么?对新手有什么建议吗?非常感谢。

采纳答案by bakkal

DateTimeField becomes a datetime.datetimeobject in Python

DateTimeField 成为datetime.datetimePython 中的对象

If you need a dateobject to manipulate later on, you could pull the datetime.dateobject directly from your DateTimeField(), using datetime.datetime.date()like below:

如果您date稍后需要一个对象来操作,您可以datetime.date直接从您的 中拉出该对象DateTimeField(),使用datetime.datetime.date()如下所示:

class ApplicantData(models.Model):
    scheduled_at = models.DateTimeField(null=True, blank=True)

date = application_data.scheduled_at.date()

This works because Django will translate the DateTimeFieldinto the Python type datetime.datetime, upon which we have called date().

这是有效的,因为 Django 会将 转换DateTimeFielddatetime.datetime我们调用的 Python 类型date()

Format the datetime.datelike you wish

datetime.date像你希望的那样格式化

Then from that, you get a datetime.dateobject, that you can format like you wish, using datetime.date.strftime().

然后,您将获得一个datetime.date对象,您可以根据需要对其进行格式化,使用datetime.date.strftime().

If you don't need a dateobject, you can also use strftimeon your datetime.datetimeobject too, no problems with that. Except that your had a None field in your object.

如果你不需要一个date对象,你也可以strftime在你的datetime.datetime对象上使用,没有问题。除了您的对象中有一个 None 字段。

Dealing with NULL/Nonefields

处理NULL/None字段

If you want to allow for NULL values in scheduled_atyou can do:

如果您想允许 NULL 值,scheduled_at您可以执行以下操作:

if application_data.scheduled_at is not None:
      date = application_data.scheduled_at.date()

回答by Shang Wang

SCHEDULED_ATis set to null=True, so sometimes item.SCHEDULED_ATdoesn't have value so it's None. If you do a .strftimeon Noneit will have the error you got. null=Truemeans django model allows the field to have NULLvalue.

SCHEDULED_AT设置为null=True,所以有时item.SCHEDULED_AT没有价值,所以它是None。如果你做一个.strftime关于None它会让你得到了错误。null=True意味着 Django 模型允许该字段具有NULL值。

By the way, it's really bad practice to use all upper case for model and field names, model name should be camel case and fields should be lower case with underscore. You model name should be ApplicantData, field name should be scheduled_at.

顺便说一句,模型和字段名称全部使用大写是非常糟糕的做法,模型名称应该是驼峰式,字段应该是带下划线的小写。您的模型名称应该是ApplicantData,字段名称应该是scheduled_at

回答by phep

While in the given example the problem is most probably due to the object truly being None, as said in other answers, please note that you might come across such a situation in test code if you forget to clean your data by calling, e.g. full_clean()on your DateTimeField as in :

虽然在给定的示例中,问题很可能是由于对象真正存在None,如其他答案中所述,请注意,如果您忘记通过调用(例如full_clean()在 DateTimeField 上)来清理数据,您可能会在测试代码中遇到这种情况如:

test_obj = YourModel(
    date=datetime.datetime(2016,2,26,tzfinfo=GM1),
    ...
)
test_obj.full_clean() # <-- don't forget this or you'll get a NoneType object
test_obj.save()