如何从DateTimeField中提取年,月,日,小时和分钟?

时间:2022-08-25 10:26:53

I would like to know how to extract the year, month, day, hour and minutes from a DateTimeField?

我想知道如何从DateTimeField中提取年,月,日,小时和分钟?

The datimefield I want to extract the info is called 'redemption_date' and the code for the model is this:

我要提取信息的datimefield称为'redemption_date',模型的代码是这样的:

from django.db import models
from datetime import datetime, timedelta
   class Code(models.Model):
        id = models.AutoField(primary_key=True)
        code_key = models.CharField(max_length=20,unique=True)
        redemption_date = models.DateTimeField(null=True, blank=True)
        user = models.ForeignKey(User, blank=True, null=True)

        # ...
        def is_expired(self):
            expired_date = datetime.now() - timedelta( days=2 )
            my_redemtion_date = self.redemption_date
            if self.redemption_date is None:
                return False
            if my_redemtion_date  < expired_date:
                    return True
            else:
                return False

Thanks in advance!

提前致谢!

3 个解决方案

#1


7  

From the datetime documentation :

从datetime文档:

[...]
class datetime.datetime
A combination of a date and a time. Attributes: year, month, day, hour, 
minute, second, microsecond, and tzinfo.
[...]

So you can extract your wanted information by directly accessing the redemption_date's attributes.

因此,您可以通过直接访问redemption_date的属性来提取您想要的信息。

#2


4  

Don't forget that your first source of information should be python itself. You can just type in your shell, after importing datetime:

不要忘记你的第一个信息来源应该是python本身。您可以在导入datetime后输入shell:

dir(datetime)
# even more detail on
help(datetime)

#3


3  

redemption_date.year
redemption_date.month
etc...

#1


7  

From the datetime documentation :

从datetime文档:

[...]
class datetime.datetime
A combination of a date and a time. Attributes: year, month, day, hour, 
minute, second, microsecond, and tzinfo.
[...]

So you can extract your wanted information by directly accessing the redemption_date's attributes.

因此,您可以通过直接访问redemption_date的属性来提取您想要的信息。

#2


4  

Don't forget that your first source of information should be python itself. You can just type in your shell, after importing datetime:

不要忘记你的第一个信息来源应该是python本身。您可以在导入datetime后输入shell:

dir(datetime)
# even more detail on
help(datetime)

#3


3  

redemption_date.year
redemption_date.month
etc...