![](/img/trans.png)
[英]How do I extract the Hour/Minute from a datetime object and get rid of the Year/Month/Day/Second section?
[英]How to extract year, month, day, hour and minutes from a DateTimeField?
我想知道如何从DateTimeField
中提取年、月、日、小时和分钟?
我要提取信息的 DateTimeField 称为“redemption_date”,model 的代码是这样的:
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
[...]
class datetime.datetime
A combination of a date and a time. Attributes: year, month, day, hour,
minute, second, microsecond, and tzinfo.
[...]
因此,您可以通过直接访问redemption_date
的属性来提取您想要的信息。
redemption_date.year
redemption_date.month
etc...
不要忘记您的第一个信息来源应该是 python 本身。 导入日期时间后,您只需输入 shell:
dir(datetime)
# even more detail on
help(datetime)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.