从Django DateTimeField获取日期 [英] Get date from a Django DateTimeField

查看:664
本文介绍了从Django DateTimeField获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想就此事寻求帮助

我正在学习django并尝试一些代码,但在尝试仅获取日期时遇到了麻烦来自模型的DateTimeField

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

这是我正在处理的代码:

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

我正在获取('NoneType'对象没有属性'strftime' ),即使我的模型包含3个都具有日期和时间的记录

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

我在做什么错呢?对新手有什么建议吗?非常感谢。

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

推荐答案

DateTimeField成为Python中的 datetime.datetime 对象



如果以后需要 date 对象进行操作,则可以拉 datetime可以直接使用DateTimeField() .date 对象datetime.html#datetime.datetime.date rel = noreferrer> datetime.datetime.date() 如下:

DateTimeField becomes a datetime.datetime object in Python

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

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

date = application_data.scheduled_at.date()

这很有用,因为Django会翻译 DateTimeField 到Python类型 datetime.datetime 中,我们在其上调用了 date()

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

然后,您将获得 datetime.date 对象,您可以使用 datetime.date.strftime()

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

如果不需要 date 对象,也可以在 datetime.datetime 上使用 strftime 也是对象,没有问题。

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

如果要在 scheduled_at 中允许使用NULL值,则可以执行以下操作:

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

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

这篇关于从Django DateTimeField获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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