Search code examples
pythondjangodjango-modelspython-datetime

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


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

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

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

Solution

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

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