Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Set datetime in views to utc+1

I have checked around a bit, both here and Google, without finding an exact answer to what I'm looking for.

I'm currently working on a Django-project and I seem to live in one of those areas where the concept of a timezone ain't regarded very highly. The timezone here is CEST, alternative: UTC+1, but neither can be set in my settings-file. I have searched around for how to change this, and one alternative is to download and include a library which should do the trick, after a bit of tweaking. But I wonder if there is a smoother, swifter way to do this.

date = datetime.datetime.now() gives me the time for two hours ago. I can use both UTC and GMT, but neither is close enough.

like image 924
Richard Atterfalk Avatar asked Apr 12 '13 20:04

Richard Atterfalk


People also ask

How do I set UTC timezone in Django?

The solution to this problem is to use UTC in the code and use local time only when interacting with end users. 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.

Is Python datetime in UTC?

Practical Data Science using PythonYou can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.

What is Use_tz in Django?

When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms. ... When django rest framework takes the naive datetime data from request.

How does Django store time zones?

Neither django nor python provide a set of timezones for you to use. For that, you will need an additional module like pytz . You can get a list of all timezones like this: >>> import pytz >>> pytz.


1 Answers

Change TIME_ZONE value according to your timezone:

UTC-2 = 'Etc/GMT+2'
UTC-2 = 'Etc/GMT+1'
UTC = 'Etc/GMT+0'
UTC+1 = 'Etc/GMT-1'
UTC+2 = 'Etc/GMT-2'

Yes, the sign is inverted after GMT. For other timezones (example half hours extra) see the TZ names.

like image 68
Punnerud Avatar answered Sep 23 '22 05:09

Punnerud