popcorn
popcorn

Reputation: 408

Django models timestamp in MYSQL Db

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.

Upvotes: 1

Views: 2126

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

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.

Upvotes: 2

Related Questions