1   
  2   
  3   
  4   
  5   
  6   
  7   
  8   
  9   
 10   
 11   
 12   
 13   
 14   
 15   
 16   
 17   
 18  """Utility functions for the pyxmpp package.""" 
 19   
 20  __revision__="$Id: utils.py 647 2006-08-26 18:27:39Z jajcus $" 
 21  __docformat__="restructuredtext en" 
 22   
 23  import sys 
 24   
 25  if sys.hexversion<0x02030000: 
 26      raise ImportError,"Python 2.3 or newer is required" 
 27   
 28  import time 
 29  import datetime 
 30   
 32      """ 
 33      Convevert `s` to UTF-8 if it is Unicode, leave unchanged 
 34      if it is string or None and convert to string overwise 
 35      """ 
 36      if s is None: 
 37          return None 
 38      elif type(s) is unicode: 
 39          return s.encode("utf-8") 
 40      elif type(s) is str: 
 41          return s 
 42      else: 
 43          return unicode(s).encode("utf-8") 
  44   
 46      """ 
 47      Convert `s` to Unicode or leave unchanged if it is None. 
 48   
 49      Regular strings are assumed to be UTF-8 encoded 
 50      """ 
 51      if s is None: 
 52          return None 
 53      elif type(s) is unicode: 
 54          return s 
 55      elif type(s) is str: 
 56          return unicode(s,"utf-8") 
 57      else: 
 58          return unicode(s) 
  59   
 60  minute=datetime.timedelta(minutes=1) 
 61  nulldelta=datetime.timedelta() 
 62   
 64      """ 
 65      An ugly hack to convert naive `datetime.datetime` object containing 
 66      UTC time to a naive `datetime.datetime` object with local time. 
 67      It seems standard Python 2.3 library doesn't provide any better way to 
 68      do that. 
 69      """ 
 70      ts=time.time() 
 71      cur=datetime.datetime.fromtimestamp(ts) 
 72      cur_utc=datetime.datetime.utcfromtimestamp(ts) 
 73   
 74      offset=cur-cur_utc 
 75      t=utc 
 76   
 77      d=datetime.timedelta(hours=2) 
 78      while d>minute: 
 79          local=t+offset 
 80          tm=local.timetuple() 
 81          tm=tm[0:8]+(0,) 
 82          ts=time.mktime(tm) 
 83          u=datetime.datetime.utcfromtimestamp(ts) 
 84          diff=u-utc 
 85          if diff<minute and diff>-minute: 
 86              break 
 87          if diff>nulldelta: 
 88              offset-=d 
 89          else: 
 90              offset+=d 
 91          d/=2 
 92      return local 
  93   
 95      """ 
 96      Simple function to convert naive `datetime.datetime` object containing 
 97      local time to a naive `datetime.datetime` object with UTC time. 
 98      """ 
 99      ts=time.mktime(local.timetuple()) 
100      return datetime.datetime.utcfromtimestamp(ts) 
 101   
102   
103