Search code examples
pythondjangodatetimedjango-timezone

Convert datetime string to with timezone in django based on active time zone


I am reading a get request and adding the data to db.

import dateutil.parser as dt

date_string = '2023-12-14 08:00:00'
date_obj = dt.parse(date_string)

It shows warning

RuntimeWarning: DateTimeField RequestLab.end_time received a naive datetime (2023-12-14 08:00:00) while time zone support is active.

Is there any way i can convert this to date object with time zone

from django.utils import timezone

curr_timezone = timezone.get_current_timezone()

and store in the db..

I tried using various methods like

datetime_obj_test1 = date_obj.replace(tzinfo=curr_timezone)
datetime_obj_test2 = date_obj.astimezone(curr_timezone)

But these 2 are changing the time i.e for timezone = "Asia/Kolkata"

datetime_obj_test1 = 2023-12-14 08:00:00+05:53

datetime_obj_test2 = 2023-12-14 19:30:00+05:30

I am expecting this as output:

2023-12-14 08:00:00+05:30


Solution

  • The warning you received indicates that you're trying to store a naive datetime (one without an associated time zone) in a DateTimeField that expects aware datetimes (with a time zone).

    Using make_aware is generally the recommended way to handle time zone conversions in Django.

    RuntimeWarning: DateTimeField RequestLab.end_time received a naive datetime (2023-12-14 08:00:00) while time zone support is active.

    Reference: https://docs.djangoproject.com/en/5.0/topics/i18n/timezones/#naive-and-aware-datetime-objects

    To convert the naive datetime to a datetime with a specific time zone in Django, you have to use the make_aware function from django.utils.timezone.

    Code:

    from django.utils import timezone
    import dateutil.parser as dt
    
    date_string = '2023-12-14 08:00:00'
    date_obj = dt.parse(date_string)
    
    curr_timezone = timezone.get_timezone("Asia/Kolkata")
    
    datetime_obj_with_timezone = timezone.make_aware(date_obj, curr_timezone)
    
    print(datetime_obj_with_timezone)
    

    Output:

    2023-12-14 08:00:00+05:30