Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the timezone aware date in django?

I am using delorean for datetime calculation in python django.

http://delorean.readthedocs.org/en/latest/quickstart.html

This is what I am using:

now = Delorean(timezone=settings.TIME_ZONE).datetime todayDate = now.date() 

But I get this warning:

RuntimeWarning: DateTimeField start_time received a naive datetime (2014-12-09 00:00:00) while time zone support is active. 

I want to know how to make it aware.

I tried this as well:

todayDate = timezone.make_aware(now.date(), timezone=settings.TIME_ZONE) 

then I get this:

AttributeError: 'datetime.date' object has no attribute 'tzinfo' 
like image 650
user3214546 Avatar asked Dec 08 '14 23:12

user3214546


People also ask

How do you make a timezone aware datetime object in Python?

Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.

How do I get the timezone from datetime?

DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means. DateTimeOffset is somewhat better - that's basically a UTC time and an offset.

How do I get specific timezone in Python?

You can get the current time in a particular timezone by using the datetime module with another module called pytz . You can then check for all available timezones with the snippet below: from datetime import datetime import pytz zones = pytz. all_timezones print(zones) # Output: all timezones of the world.


1 Answers

It's not clear whether you're trying to end up with a date object or a datetime object, as Python doesn't have the concept of a "timezone aware date".

To get a date object corresponding to the current time in the current time zone, you'd use:

# All versions of Django from django.utils.timezone import localtime, now localtime(now()).date()  # Django 1.11 and higher from django.utils.timezone import localdate localdate() 

That is: you're getting the current timezone-aware datetime in UTC; you're converting it to the local time zone (i.e. TIME_ZONE); and then taking the date from that.

If you want to get a datetime object corresponding to 00:00:00 on the current date in the current time zone, you'd use:

# All versions of Django localtime(now()).replace(hour=0, minute=0, second=0, microsecond=0)  # Django 1.11 and higher localtime().replace(hour=0, minute=0, second=0, microsecond=0) 

Based on this and your other question, I think you're getting confused by the Delorean package. I suggest sticking with Django's and Python's datetime functionality.

like image 116
Kevin Christopher Henry Avatar answered Sep 26 '22 00:09

Kevin Christopher Henry