django - make datetimefield accept unix timestamp

后端 未结 2 786
青春惊慌失措
青春惊慌失措 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()
    
    0 讨论(0)
  • 2021-01-18 17:22

    The pip package django-unixdatetimefield provides a UnixDateTimeField field that you can use for this out of the box (https://pypi.python.org/pypi/django-unixdatetimefield/).

    Example model:

    from django_unixdatetimefield import UnixDateTimeField
    
    class MyModel(models.Model):
        created_at = UnixDateTimeField()
    

    Python ORM query:

    >>> m = MyModel()
    >>> m.created_at = datetime.datetime(2015, 2, 21, 19, 38, 32, 209148)
    >>> m.save()
    

    Database:

    sqlite> select created_at from mymodel;
    1426967129
    

    Here's the source code if interested - https://github.com/Niklas9/django-unixdatetimefield.

    Disclaimer: I'm the author of this pip package.

    0 讨论(0)
提交回复
热议问题