Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a datetime object is localized with pytz?

I want to store a datetime object with a localized UTC timezone. The method that stores the datetime object can be given a non-localized datetime (naive) object or an object that already has been localized. How do I determine if localization is needed?

Code with missing if condition:

class MyClass:   def set_date(self, d):     # what do i check here?     # if(d.tzinfo):       self.date = d.astimezone(pytz.utc)     # else:       self.date = pytz.utc.localize(d) 
like image 774
chiborg Avatar asked Apr 27 '11 09:04

chiborg


People also ask

What does pytz UTC localize do?

localize() pytz. localize() is useful for making a naive timezone aware. it is useful when a front-end client sends a datetime to the backend to be treated as a particular timezone (usually UTC).

How do you know if a datetime is naive or aware?

The easiest way to tell if a datetime object is naive is by checking tzinfo. tzinfo will be set to None of the object is naive. To make a datetime object offset aware, you can use the pytz library.


1 Answers

How do I determine if localization is needed?

From datetime docs:

  • a datetime object d is aware iff:

    d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None 
  • d is naive iff:

    d.tzinfo is None or d.tzinfo.utcoffset(d) is None 

Though if d is a datetime object representing time in UTC timezone then you could use in both cases:

self.date = d.replace(tzinfo=pytz.utc) 

It works regardless d is timezone-aware or naive.

Note: don't use datetime.replace() method with a timezone with a non-fixed utc offset (it is ok to use it with UTC timezone but otherwise you should use tz.localize() method).

like image 120
jfs Avatar answered Sep 30 '22 07:09

jfs