0

I am facing some issues with time formats in django.

My models DateTimeField is using auto_now to store datetime and I am trying to filter data using this datetimefield. The input datetime which I am using to comapre is in differenr format like 2016-1-5T5:00:00 and datetime stored in djnago models is default django format since I am using auto_now. The error I am getting is as follows :

RuntimeWarning: DateTimeField MyModel.modified_at received a naive datetime (2016-01-05 05:00:00) while time zone support is active.
  RuntimeWarning)

So I guess I need to convert the input time into django suitable format. Any idea how I can compare these two dates so that my query can filter correct data.

user5594493
  • 1,050
  • 3
  • 10
  • 24
  • @AmalTs I ahve tgried that part but when I'll do this `datetime.datetime(my_time_inut)` I'll get error saying str not allowed – user5594493 Jan 07 '16 at 06:12
  • But are you using from `django.utils import timezone`? – Amal Ts Jan 07 '16 at 06:17
  • @AmalTs yes from utils – user5594493 Jan 07 '16 at 06:25
  • @user5594493: `datetime(my_time_input)` is a different question. You can ask a separate question e.g., "how to get a timezone-aware datetime object given `my_time_input`". Make sure to describe what `my_time_input` is (is it a string? is it a returned value from an API call? etc). – jfs Jan 07 '16 at 06:45
  • @J.F.Sebastian yes I am getting input from API call and its format is mentioned in question -> 2016-1-5T5:00:00 – user5594493 Jan 07 '16 at 07:08
  • I don't understand what you mean by the word "format": does it mean `type(my_time_input)` is `str`? `RuntimeWarning: DateTimeField MyModel.modified_at received a naive datetime` indicates that you already have a `datetime` object (`type(obj) == datetime`, not `str`). `TypeError: an integer is required (got type str)` (e.g., due to `datetime('2016-1-5T5:00:00')`) is a different issue. If you get `TypeError` then you should fix it first. – jfs Jan 07 '16 at 07:44

1 Answers1

1

Have you tried using a timezone aware datetime? e.g.

datetime.datetime(2013, 11, 20, 20, 8, 7, 127325, tzinfo=<UTC>)

You can make it like this:

import pytz
timezone_aware_time = pytz.timezone('UTC').localize(datetime.datetime(2013, 11, 20, 20, 8, 7, 127325))

To get your string into a compliant format and then give it a timezone, do this:

import datetime from datetime
datetime.strptime('2016-1-5T5:00:00', '%Y-%m-%dT%H:%M:%S')

So, altogether:

import pytz
import datetime from datetime
timezone_aware_time = pytz.timezone('UTC').localize(datetime.strptime('2016-1-5T5:00:00', '%Y-%m-%dT%H:%M:%S'))

For reference, auto_now is in timezone UTC.

Morifen
  • 126
  • 1
  • 7