簡體   English   中英

如何從 DateTimeField 中提取年、月、日、小時和分鍾?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM