2

I am new to Django. I would have better grasp of this in Rails but am not familiar enough with all the libraries and converstions in Python / Django.

I have a model:

class Status(models.Model):
  created = models.DatetimeField(auto_now_add=True)

This results in the format:

"created": "2017-01-06T22:21:51.531723Z"

I was hoping to see if before saving to the DB that it stores as a UNIX value?

This looked promising https://stackoverflow.com/a/34843855/3007294 but can't get it working. Every time I try to create a Status object, I get this error:

Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].

My intentions are to not have to enter this every time a Status object is created.

Thanks -

Community
  • 1
  • 1
user3007294
  • 931
  • 1
  • 14
  • 33
  • 2
    It's not clear what you are asking. The field will be saved as the database's datetime format. You don't have to do anything at all. – Daniel Roseman Jan 06 '17 at 22:47
  • @DanielRoseman I was hoping to save the field as a UNIX timestamp (converted from the datetime format). – user3007294 Jan 06 '17 at 23:20

1 Answers1

4

My intentions are to not have to enter this every time a Status object is created.

This is already taken care of with the auto_now_add=True option. When you create a Status object, the created field will be populated with the current datetime.

I was hoping to see if before saving to the DB that it stores as a UNIX value?

You can convert the datetime value from Status.created to a Unix timestamp anytime required. Storing it in the default database datetime format (which is what DatetimeField does) is generally preferred to storing it as a timestamp, which is just an integer.

However, the library used in the example you provided, django-unixdatetimefield, states that "UnixDateTimeField is based on the implementation of the standard Django DateTimeField, making it 100% compatible with all features and options it supports." So, you should be able to provide the auto_now_add=True option to that field.

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94