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 __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
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
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
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
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
102