Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a naive datetime in Django 1.4

I have a naive date and time in the format '2012-05-19 19:13:00' and need to store it using Django 1.4 and its timezone-aware abilities.

Although there is no way of knowing what timezone the date is originally in, it seems to make sense to store it as if it were UTC.

However, using pytz etc, I'm not sure how to convert a date that has no timezone into a UTC datetime.

like image 742
Phil Gyford Avatar asked May 19 '12 18:05

Phil Gyford


People also ask

How does Django store current date and time?

First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value.

What is a naive datetime Python?

Timezone-Aware datetime object: does have a timezone associated with it. Timezone-Naïve datetime object: does not have any timezone associated with it. Rules of thumb. Always work with "timezone-aware" datetime objects. Always store datetime in UTC and leave rendering of timezones to the front-end.

How do I get UTC time in Django?

The solution to this problem is to use UTC in the code and use local time only when interacting with end users. Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. In Django 5.0, time zone support will be enabled by default.

What is pytz in Django?

pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference ( datetime. tzinfo ).


1 Answers

If it has no tzinfo then of course there can be no conversion to UTC. Instead you could just make the datetime object into an time-zone aware one:

import datetime
from pytz import UTC

dt = datetime.datetime.now()  # just some date
tz_aware_dt = dt.replace(tzinfo=UTC)

Edit:

The migration guide for django 1.4 uses this to accomplish the above:

>>> from django.utils.dateparse import parse_datetime
>>> naive = parse_datetime("2012-02-21 10:28:45")
>>> import pytz
>>> pytz.timezone("Europe/Helsinki").localize(naive)
datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=<DstTzInfo 'Europe/Helsinki' EET+2:00:00 STD>)

You should probably use that version, substituting "Europe/Helsinki" for "UTC".

like image 200
XORcist Avatar answered Sep 23 '22 21:09

XORcist