Django Learner
Django Learner

Reputation: 323

How can I make django model datetime field data of midnight and timezone aware?

I am trying to set expire_time in my django model to be midnight of user's selected date with timezone aware. But I am not able to get it properly. Can anyone tell me how I can do it or where I am making mistake in my code?

My codes are,

date = datetime.strptime(str(request.POST.get('expire') + ', 23:59:59'),
                                     '%Y-%m-%d, %H:%M:%S')
            tz = timezone.get_current_timezone()
            date_tz = tz.localize(date)
            createEventInDB.ev_expire = date_tz

            try:
                createEventInDB.save()

            except Exception as e:
                error = e

So if I select date which is December 1st 2015, it would be posting as 2015-12-1

I want to save data in database like 2015-12-01 23:59:59. I want to give whole day to user. My current timezone is America/Chicago. I have set active timezone by ip. So I want to make it like user can post from anywhere but timezone must be UTC aware and expire at midnight. Can anyone tell me how can I make it possible?

Upvotes: 0

Views: 1510

Answers (2)

jfs
jfs

Reputation: 414695

I want to do is 2015-12-01 23:59:59 utc

Your code in the question returns 23:59:59 in the current time zone.

It is even simpler to return "23:59:59 UTC" instead given the corresponding UTC date:

from datetime import datetime
import pytz

ev_expire = datetime(utc_date.year, utc_date.month, utc_date.day, 23, 59, 59,
                     tzinfo=pytz.utc)

Upvotes: 1

Behzad
Behzad

Reputation: 89

based on the documentation at https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/

When support for time zones is enabled, 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.

So all this is completely unnecessary and all you need to do is use the models.DateTimeField like you always did.

You can define a Date widget in the view or form and alter Time of DateTimeField later on to 23:59:59 before saving (or you can provide it as a default) and Django will automatically convert it to UTC before saving.

Upvotes: 2

Related Questions