5

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 input in DataTimeField

i.e. i don't see how adding '%s' as an input format will work, especially when the code for to_python() of the standard datetime field doesn't include any logic for handling unix timestamps.

If there is a setting that allows me to do this great.
Otherwise, what I think i want is to subclass DateTimeField and somehow automatically convert the int to a datetime object when i set the value. I want to do this before saving instead of overriding save() because i want consistency when retrieving the value of this field. i.e. when I take the value out, I don't want to worry about if i have a datetime object or an int regardless of if the instance has been saved or not.

I looked at source of django.db.models.fields and it's not apparent to me.

Community
  • 1
  • 1
w--
  • 6,427
  • 12
  • 54
  • 92
  • possible duplicate http://stackoverflow.com/questions/11332107/timestamp-fields-in-django – Adem Öztaş Aug 24 '15 at 09:31
  • not a duplicate. i want to retain everything about the current datetimefield. i just want the option of setting the value via an integer value that represents a unix timestamp with the requirements outlined above – w-- Aug 24 '15 at 10:04

2 Answers2

10

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.

Niklas9
  • 8,816
  • 8
  • 37
  • 60
  • I am trying to insert data from Django Rest Framework, and when I send the payload: `{ "timeStamp": 1581950810, } ` I get this error: `{ "timeStamp": [ "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." ] }` Is it possible to accept timestamp on the field? – Bruno Feb 17 '20 at 20:21
  • You're using it the wrong way. If you need to send unix timestamps to your API, you should use Django Rest Framework to handle it, no need to use this library. – Niklas9 Feb 18 '20 at 22:08
3

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()
Ben Beirut
  • 733
  • 3
  • 12
  • Thanks Ben. Using this pre_save method on the field, if the instance has not been saved yet, will the attribute value still be converted to a datetime object? i.e. if i do obj.timestamp = , when i attempt to retrieve the value of obj.timestamp before saving it, will I get a datetime object back? – w-- Aug 24 '15 at 17:25
  • No. Only after you save it will you be able to get a datetime object back. Can you explain the use case and why it would be so advantageous to change what the assignment operator does? It seems like a very serious modification you want to add. – Ben Beirut Aug 25 '15 at 11:45