Python string to Django timezone (aware datetime) Python string to Django timezone (aware datetime) django django

Python string to Django timezone (aware datetime)


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 datetimefrom django.utils.timezone import make_awaredate = '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.


You are comparing time-zone unaware Python Date objects with the time-zone aware DateTimeField fields in your database. It is probably more intuitive to use DateTime objects - and these can be made time-zone aware easily as follows:

import datetimeimport pytzstart_date = '15-01-2016' end_date = '16-01-2016'date_format = '%d-%m-%Y'unaware_start_date = datetime.datetime.strptime(start_date, date_format)aware_start_date = pytz.utc.localize(unaware_start_date)unaware_end_date = datetime.datetime.strptime(end_date, date_format)aware_end_date = pytz.utc.localize(unaware_end_date)my_list = MyModel.objects.filter(created_at__range=(aware_start_date, aware_end_date))

This creates unaware_start_date and unaware_end_date DateTime objects using strptime(). It then uses pytz.utc.localize to make the objects time-zone aware (you will need to replace utc with your relevant time-zone).

You can then have time-zone aware DateTime objects - aware_start_date and aware_end_date. Feeding these into your filter should yield the desired results.


from django.utils import timezonetimestamp_raw = timezone.now() #current time, or use whatever time you havedate_format = '%Y-%m-%d %H:%M:%S' #time format day-month-year hour:minutes:secondstimestamp = timezone.datetime.strftime(timestamp_raw, date_format)

Or Using the new f-string formatter

f"{timezone:%Y-%m-%d %H:%M:%S %p}"