0

How can I save in this unix epoch datetimeformat like this

2019-11-12T10:26:39.613Z

into models.DateTimeField accurately

I tried with this but as you can see, assigning with datetime.datetime.strptime seems correct, but after I save it, the datetime value changes (which is then inaccurate)

>>> b.updated_at = datetime.datetime.strptime("2019-11-12T10:26:39.613Z", '%Y-%m-%dT%H:%M:%S.%fZ')
>>> b.updated_at
datetime.datetime(2019, 11, 12, 10, 26, 39, 613000)
>>> b.save()
>>> b.updated_at
datetime.datetime(2019, 11, 12, 3, 1, 35, 82434, tzinfo=<UTC>)

in model.py

updated_at = models.DateTimeField(auto_now=True)

I am using Django 1.11 and Postgres 9.4

Axil
  • 3,606
  • 10
  • 62
  • 136

1 Answers1

0

Your problem is not with your date formats. Your problem is that you've declared your field to be auto_now=True. That causes Django to always set it to the current time when saving, overriding the in-memory value. From the docs:

Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.

That last sentence describes your observed behavior. You can't easily change it while keeping the field set to auto_now=True - if you want to automatically update that field on some saves but not all, I think a custom save method on your model is the best option.

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
  • thanks. it was just a test field. ok, it worked on other models.DateTimeField. Thanks – Axil Nov 12 '19 at 03:52