django - make datetimefield accept unix timestamp

后端 未结 2 785
青春惊慌失措
青春惊慌失措 2021-01-18 17:05

i\'d like to make the DateTimefield of models accept unix timestamp (in seconds) values.

I found this but the acepted solution doesn\'t work?
unixtimestamp inp

2条回答
  •  孤街浪徒
    2021-01-18 17:21

    Using UNIX timestamp as values for DateTimeField should probably come with Django by default. Django’s introspection is really powerful but makes things less obvious than desirable, especially in the context of Python code.

    You can achieve it by subclassing DateTimeField and overriding the pre_save method.

    from django.db import models
    from datetime import datetime
    
    from django.db.models.fields import DateTimeField
    
    class UCDateTimeField(DateTimeField):
    
        def pre_save(self, model_instance, add):
            if self.auto_now or (self.auto_now_add and add):
                value = datetime.datetime.now()
                setattr(model_instance, self.attname, value)
                return value
            else:
                value = getattr(model_instance, self.attname)
                if not isinstance(value, datetime):
                    # assume that the value is a timestamp if it is not a datetime
                    value = datetime.fromtimestamp(int(value))
                    # an exception might be better than an assumption
                    setattr(model_instance, self.attname, value)
                return super(UCDateTimeField, self).pre_save(model_instance, add)
    
    
    class Event(models.Model):
        date = UCDateTimeField()
    

提交回复
热议问题