Package pyxmpp :: Module utils
[hide private]

Source Code for Module pyxmpp.utils

  1  # 
  2  # (C) Copyright 2003-2010 Jacek Konieczny <jajcus@jajcus.net> 
  3  # 
  4  # This program is free software; you can redistribute it and/or modify 
  5  # it under the terms of the GNU Lesser General Public License Version 
  6  # 2.1 as published by the Free Software Foundation. 
  7  # 
  8  # This program is distributed in the hope that it will be useful, 
  9  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 10  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 11  # GNU Lesser General Public License for more details. 
 12  # 
 13  # You should have received a copy of the GNU Lesser General Public 
 14  # License along with this program; if not, write to the Free Software 
 15  # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
 16  # 
 17   
 18  """Utility functions for the pyxmpp package.""" 
 19   
 20  __docformat__="restructuredtext en" 
 21   
 22  import sys 
 23   
 24  if sys.hexversion<0x02030000: 
 25      raise ImportError,"Python 2.3 or newer is required" 
 26   
 27  import time 
 28  import datetime 
 29   
30 -def to_utf8(s):
31 """ 32 Convevert `s` to UTF-8 if it is Unicode, leave unchanged 33 if it is string or None and convert to string overwise 34 """ 35 if s is None: 36 return None 37 elif type(s) is unicode: 38 return s.encode("utf-8") 39 elif type(s) is str: 40 return s 41 else: 42 return unicode(s).encode("utf-8")
43
44 -def from_utf8(s):
45 """ 46 Convert `s` to Unicode or leave unchanged if it is None. 47 48 Regular strings are assumed to be UTF-8 encoded 49 """ 50 if s is None: 51 return None 52 elif type(s) is unicode: 53 return s 54 elif type(s) is str: 55 return unicode(s,"utf-8") 56 else: 57 return unicode(s)
58 59 minute=datetime.timedelta(minutes=1) 60 nulldelta=datetime.timedelta() 61
62 -def datetime_utc_to_local(utc):
63 """ 64 An ugly hack to convert naive `datetime.datetime` object containing 65 UTC time to a naive `datetime.datetime` object with local time. 66 It seems standard Python 2.3 library doesn't provide any better way to 67 do that. 68 """ 69 ts=time.time() 70 cur=datetime.datetime.fromtimestamp(ts) 71 cur_utc=datetime.datetime.utcfromtimestamp(ts) 72 73 offset=cur-cur_utc 74 t=utc 75 76 d=datetime.timedelta(hours=2) 77 while d>minute: 78 local=t+offset 79 tm=local.timetuple() 80 tm=tm[0:8]+(0,) 81 ts=time.mktime(tm) 82 u=datetime.datetime.utcfromtimestamp(ts) 83 diff=u-utc 84 if diff<minute and diff>-minute: 85 break 86 if diff>nulldelta: 87 offset-=d 88 else: 89 offset+=d 90 d/=2 91 return local
92
93 -def datetime_local_to_utc(local):
94 """ 95 Simple function to convert naive `datetime.datetime` object containing 96 local time to a naive `datetime.datetime` object with UTC time. 97 """ 98 ts=time.mktime(local.timetuple()) 99 return datetime.datetime.utcfromtimestamp(ts)
100 101 # vi: sts=4 et sw=4 102