1

I want to store time as unix timestamp in my MYSQL database, I have django project with model:

date = models.DateField()

But I didn't find any models.Timestamp() or anything similiar. Is there a way to create timestamp column for MYSQL Db in Django? I found some articles here on stack but they are 5+ years old so there might a be a better solution now.

1
  • 2
    Usually a DateTimeField is used, a timestamp can represent only a subset of the datetime values. Commented Oct 2, 2019 at 11:27

1 Answer 1

2

In Django, one usually uses a DateTimeField [Django-doc] for that. It is a column that thus stores a combination of date and time.

One can let Django automatically intialize (or update) the timestamp if the record is constructed or updated with auto_now_add=True [Django-doc] to initialize it when the record was created, and auto_now=True [Django-doc] to update. So it is a common pattern to see a (base)model like:

class TimestampModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

such that subclasses of the TimestampModel thus have two extra columns created and updated that store the time when the object was created and last updated respectively.

A datetime column has a larger range, as is specified in the MySQL documentation:

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD hh:mm:ss' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.