Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string to Django timezone (aware datetime)

TL;DR;

How to convert 2016-01-01 to Django timezone?

Full version:

I receive a query string parameter from a form and I wanna get that string and use it as a datetime filter in Django. The problem is that when I convert the string to a datetime, it's not making an aware datetime and so I lose a few hours due to timezone different. Maybe I'm losing myself in the formatting, but I'm not being able to do it.

I have pytz, I have USE_TZ = True in my settings as well.

example:

from datetime import date # Example from what I receive as GET querystring parameter start_date, end_date = '15-01-2016', '16-01-2016' DATE_FORMAT = '%Y-%m-%d' start_date = start_date.split('-') start_date = date(int(start_date[2]), int(start_date[1]), int(start_date[0])) sd_filter = start_date.strftime(DATE_FORMAT)  end_date = end_date.split('-') end_date = date(int(end_date[2]), int(end_date[1]), int(end_date[0])) ed_filter = end_date.strftime(DATE_FORMAT)  #query my_list = MyModel.objects.filter(created_at__range=(sd_filter, ed_filter)) 

the problem lies in the filter. I'm losing a few hours due to timezone from Django settings.

UPDATE: I don't need to convert a datetime.now() to my time. I need to convert a string to datetime.

like image 348
jarussi Avatar asked Jan 15 '16 18:01

jarussi


People also ask

How do you make a timezone aware datetime object in Python?

Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.

How do I set timezone in Django?

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. Time zone support uses zoneinfo , which is part of the Python standard library from Python 3.9.


1 Answers

I know this is old but maybe will be helpful since I got into this situation as well:

What about using make_aware() ?

from datetime import datetime from django.utils.timezone import make_aware  date = '22-05-2018' aware = make_aware(datetime.strptime(date, '%d-%m-%Y')) 

This will use the currently active timezone (activated by timezone.activate). If no timezone is activated explicitly, it would use the default timezone -- TIME_ZONE specified in settings.py.

like image 87
Gustavo A. Díaz Avatar answered Sep 23 '22 05:09

Gustavo A. Díaz