Loaddata does not apply to timestamps and clocks.

I am using django 1.4.1 with mysql and timezones enabled. I made dump data in yaml, changed some fields to create some test data, and try to load them back. However, Django continues to complain about naive dates, even if tz is specified

in particular, my loaddata has:

fields: {created_date: !!timestamp '2012-09-15 22:17:44+00:00', ...

but loaddata gives an error:

RuntimeWarning: DateTimeField received a naive datetime (2012-09-15 22:17:44) while time zone support is active.

It doesn't really matter to me seeing it:

  • UTC timestamp
  • exact Django format exported using dumpdata li>

is there any way i can tell django is the UTC date?

+6
source share
4 answers

From docs ...

When serializing a signed date-time, the UTC offset is turned on, for example this:

"2011-09-01T13:20:30+03:00"

datetime , , :

"2011-09-01T13:20:30"

... ...

created_date: !!timestamp '2012-09-15 22:17:44+00:00'

... ...

created_date: '2012-09-15T22:17:44+00:00'

... ...

created_date: '2012-09-15T22:17:44Z'

... .

+8

PyYAML. loaddata datetime PyYAML, datetime, UTC, datetime, .

Django ticket, PyYAML . . , .

TIME_ZONE = 'UTC' settings.py , , . - , Django - UTC, , , .

- JSON .

, .

+20

django/core/serializers/pyyaml.py , (, 78-79 .1.9.9)

for obj in PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options):
    yield obj

output = yaml.load(stream, Loader=SafeLoader)
for a_model in output:
    for key, value in a_model.items():
        if key == 'fields':
            for vkey, vvalue in value.items():
                if isinstance(vvalue, datetime.datetime):
                    value[vkey] = vvalue.replace(tzinfo=pytz.utc)
for obj in PythonDeserializer(output, **options):
    yield obj

, pytz

import pytz

.

datetime UTC.

, SERIALIZATION_MODULES settings.py:

SERIALIZATION_MODULES = {'yaml': 'yourproj.pyyaml'}

I hope this monkey patch works great.

+1
source

I wanted to continue to use YAML instead of JSON to be able to leave comments in the data. The workaround from here solved the problem for me: https://code.djangoproject.com/ticket/18867

Namely, manually changing the YAML device so that it:

  • Doesn't use YAML tag timestamps!
  • Encloses timestamp values ​​in quotation marks
  • Includes time zone information in the timestamp value

... and, obviously, this triggers the Django timestamp parsing logic instead of the broken PyYAML logic.

0
source

All Articles