如何将这样的 unix epoch datetimeformat (2019-11-12T10:26:39.613Z) 准确保存到 models.DateTimeField

How to save unix epoch datetimeformat like this (2019-11-12T10:26:39.613Z) into models.DateTimeField accurately

我怎样才能像这样保存在这个 unix 纪元日期时间格式中

2019-11-12T10:26:39.613Z

准确models.DateTimeField

我试过这个,但正如你所见,用 datetime.datetime.strptime 分配似乎是正确的,但在我保存它之后,日期时间值发生变化(然后不准确)

>>> 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>)

在model.py

updated_at = models.DateTimeField(auto_now=True)

我正在使用 Django 1.11 和 Postgres 9.4

您的问题不在于日期格式。您的问题是您已将字段声明为 auto_now=True。这导致 Django 在保存时始终将其设置为当前时间,覆盖内存中的值。来自 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.

最后一句话描述了您观察到的行为。您不能在将字段设置为 auto_now=True 的同时轻松更改它 - 如果您想在某些但不是全部保存时自动更新该字段,我认为您的模型上的自定义 save 方法是最好的选项。