0

I am trying to create a record in my Django project with the timezone set to Europe/Rome.

When I create the model object, I use this function to set the timezone:

MyModel.objects.create(
    name="trial",
    date=datetime_aware("2023-08-15")
)

However, I am encountering an issue where the record is being stored with the date "2023-08-14" and the UTC timezone (GMT), despite my efforts to set it to Europe/Rome.

In order to do this, I first set the following values in my settings.py file:

USE_TZ = True
TIME_ZONE = "Europe/Rome"

Next, I wrote a function to create a datetime object with the appropriate timezone:

def datetime_aware(dt_string, timezone=settings.TIME_ZONE):
    if dt_string:
        dt = datetime.datetime.strptime(dt_string, "%Y-%m-%d")
        dt_aware = make_aware(dt, pytz.timezone(timezone))
        return dt_aware
    return None

Can you help me figure out what's going wrong?

Gimbo
  • 13
  • 5
  • Times are always normalized to UTC for database storage, because none of the supported database backends support storing localized times. Your problem is likely that you’re storing just a date, but create a datetime‽ That datetime converted to UTC might be a different day, and you’re only storing the date portion of it. – deceze May 03 '23 at 08:28
  • If you just need a date, just create a date. That doesn’t have to deal with time zones. – deceze May 03 '23 at 08:30
  • @deceze Thanks for your response. To clarify, I initially attempted to create the record with just the date (without specifying the timezone, except in settings with TIME_ZONE variable). However, even in this case, Django stored the record with UTC timezone and the date 14-08-2023, instead of the expected timezone Europe/Rome and the date 15-08-2023. – Gimbo May 03 '23 at 08:34
  • What exactly is happening would probably be easier to comprehend if you didn't discard the time part of the datetime… Without it, one can only say something-something-timezone-conversion-at-some-point. – deceze May 03 '23 at 08:38

1 Answers1

0

in first section it does seems like your Django project is using the default time zone, it may not work effectively even if you set time zone separately. in bellow the function you created looks ok there might be the issue with the string that you are passing here dt_string:

dt = datetime.datetime.strptime(dt_string, "%Y-%m-%d")
dt_aware = make_aware(dt, pytz.timezone(timezone))

may have different time zone than Europe/Rome 
You may try this code:

def my_model():
tz = pytz.timezone("Europe/Rome")
date = datetime(2023,5,3,tzinfo=tz)
mModel.objects.create(name="trial",date=dt))

this might be helpful