How to extract year, month, day, minutes and minutes from DateTimeField?

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

The datimefield field I want to retrieve is called "redemption_date", and the code for the model is as follows:

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!

+5
source share
3 answers

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.
[...]

Thus, you can extract the necessary information by directly accessing the attributes redemption_date.

+7
source

Remember that your first source of information should be python itself. You can simply enter the shell after importing datetime:

dir(datetime)
# even more detail on
help(datetime)
+4
source
redemption_date.year
redemption_date.month
etc...
+3
source

All Articles