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

标签 python django

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

我要提取信息的日期字段称为“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

提前致谢!

最佳答案

From the datetime documentation :

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

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

关于python - 如何从 DateTimeField 中提取年、月、日、小时和分钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11218305/

相关文章:

python - PyTorch - 尽管检测到 CUDA 支持,但张量并未使用 GPU

python - 如何在python脚本中检查系统是否为FreeBSD?

python - 使用 value_counts() 查找 pandas 中的类准确性

python - 在控制台中获取python子进程的输出

python - 如何迭代 Pandas 数据框的列以运行回归

python - 反转 '',参数 '' 和关键字参数 '{}' 未找到

Django - 动态导入模型表单

django - 如何在 django 的 CreateView 中使用上下文与类?

python - Django:如何访问和显示一对多关系中单个 "child"的详细信息?

python - 如何删除字符串中某个字符后的所有内容?