Home > Back-end >  Convert timestamp to correct datetime in local timezone - Django
Convert timestamp to correct datetime in local timezone - Django

Time:11-11

I get a timestamp from an API. When I transform it with:

timestamp = datetime.fromtimestamp(json.loads(m)["_timestamp"], tz=pytz.timezone('Europe/Berlin')) 

I get the correct time in the console when I print it:

2021-11-10 15:22:26 01:00

But when I save it to the database with:

BedTemperatureHistory.objects.create(TimeStamp=timestamp)

The Timestamp looks something like this in the database (one hour less):

2021-11-10 14:22:26.000000  00:00 

My Timezone Settings look like this:

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Europe/Berlin'

USE_I18N = True

USE_L10N = True

USE_TZ = False

Does anyone know what I need to do in order to save the correct timestamp in my database?

CodePudding user response:

You need to enable time zone support in your settings.

USE_TZ = True

EDIT: The timestamp is actually stored correctly in your question. You will note that the two times are actually the same, 15:22 01:00 is the same as 14:22 00:00. Django stores datetimes in UTC, to avoid issues with daylight savings:

Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.

  • Related