Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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

The datimefield 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

Thanks in advance!

like image 579
ipegasus Avatar asked Jun 27 '12 01:06

ipegasus


People also ask

How do I get hours and minutes from datetime?

How to Get the Current Time with the datetime Module. To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.

How do you extract hours from date time?

Extract time only from datetime with formula 1. Select a blank cell, and type this formula =TIME(HOUR(A1),MINUTE(A1), SECOND(A1)) (A1 is the first cell of the list you want to extract time from), press Enter button and drag the fill handle to fill range.

How do I extract time from a Dataframe in Python?

arg: It can be integer, float, tuple, Series, Dataframe to convert into datetime as its datatype. format: This will be str, but the default is None. The strftime to parse time, eg “%d/%m/%Y”, note that “%f” will parse all the way up to nanoseconds.

How can I get minutes in C#?

DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20); DateTime date2 = new DateTime(2018, 8, 17, 11, 14, 25); Now, calculate the difference between two dates. TimeSpan ts = date2 - date1; To calculate minutes.


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

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

like image 180
azmo Avatar answered Sep 21 '22 05:09

azmo