forked from limodou/uliweb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdate.py
More file actions
262 lines (221 loc) · 6.8 KB
/
date.py
File metadata and controls
262 lines (221 loc) · 6.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import time, re
from datetime import tzinfo, timedelta, datetime, date, time as time_
from sorteddict import SortedDict
__timezone__ = None
__local_timezone__ = None
__timezones__ = SortedDict()
class DateError(Exception):pass
class TimeFormatError(Exception):pass
DEFAULT_DATETIME_INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.5200'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%Y/%m/%d %H:%M:%S', # '2006/10/25 14:30:59'
'%Y/%m/%d %H:%M:%S.%f', # '2006/10/25 14:30:59.5200'
'%Y/%m/%d %H:%M', # '2006/10/25 14:30'
'%Y/%m/%d', # '2006/10/25 '
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.5200'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.5200'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
'%H:%M:%S', # '14:30:59'
'%H:%M', # '14:30'
)
ZERO = timedelta(0)
class UTCTimeZone(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
def __repr__(self):
return '<tzinfo UTC>'
UTC = UTCTimeZone()
class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
def __repr__(self):
return "<tzinfo %s>" % self.__name
for i in range(-12, 13):
if i == 0:
continue
if i>0:
k = 'GMT +%d' % i
else:
k = 'GMT %d' % i
__timezones__[k] = FixedOffset(i*60, k)
__timezones__['UTC'] = UTC
re_timezone = re.compile(r'GMT\s?([+-]?)(\d+)', re.IGNORECASE)
def fix_gmt_timezone(tz):
if isinstance(tz, (str, unicode)):
b = re_timezone.match(tz)
if b:
n = b.group(2)
if n == '0':
return 'UTC'
sign = b.group(1)
if not sign:
sign = '+'
return 'GMT ' + sign + n
return tz
def set_timezone(tz):
global __timezone__
__timezone__ = timezone(tz)
def get_timezone():
return __timezone__
def set_local_timezone(tz):
global __local_timezone__
__local_timezone__ = timezone(tz)
def get_local_timezone():
return __local_timezone__
def get_timezones():
return __timezones__
def register_timezone(name, tz):
__timezones__[name] = tz
def timezone(tzname):
if not tzname:
return None
if isinstance(tzname, (str, unicode)):
#not pytz module imported, so just return None
tzname = fix_gmt_timezone(tzname)
tz = __timezones__.get(tzname, None)
if not tz:
raise DateError, "Can't find tzname %s" % tzname
return tz
elif isinstance(tzname, tzinfo):
return tzname
else:
raise DateError, "Unsupported tzname %r type" % tzname
def pick_timezone(*args):
for x in args:
tz = timezone(x)
if tz:
return tz
def now(tzinfo=None):
tz = pick_timezone(tzinfo, __timezone__)
return datetime.now(tz)
def today(tzinfo=None):
d = now(tzinfo)
return to_date(d, tzinfo)
def to_timezone(dt, tzinfo=None):
"""
Convert a datetime to timezone
"""
if not dt:
return dt
tz = pick_timezone(tzinfo, __timezone__)
if not tz:
return dt
dttz = getattr(dt, 'tzinfo', None)
if not dttz:
return dt.replace(tzinfo=tz)
else:
return dt.astimezone(tz)
def to_date(dt, tzinfo=None, format=None):
"""
Convert a datetime to date with tzinfo
"""
d = to_datetime(dt, tzinfo, format)
if not d:
return d
return date(d.year, d.month, d.day)
def to_time(dt, tzinfo=None, format=None):
"""
Convert a datetime to time with tzinfo
"""
d = to_datetime(dt, tzinfo, format)
if not d:
return d
return time_(d.hour, d.minute, d.second, d.microsecond, tzinfo=d.tzinfo)
def to_datetime(dt, tzinfo=None, format=None):
"""
Convert a date or time to datetime with tzinfo
"""
if not dt:
return dt
tz = pick_timezone(tzinfo, __timezone__)
if isinstance(dt, (str, unicode)):
if not format:
formats = DEFAULT_DATETIME_INPUT_FORMATS
else:
formats = list(format)
d = None
for fmt in formats:
try:
d = datetime.strptime(dt, fmt)
except ValueError:
continue
if not d:
return None
d = d.replace(tzinfo=tz)
else:
d = datetime(getattr(dt, 'year', 1970), getattr(dt, 'month', 1),
getattr(dt, 'day', 1), getattr(dt, 'hour', 0), getattr(dt, 'minute', 0),
getattr(dt, 'second', 0), getattr(dt, 'microsecond', 0))
if not getattr(dt, 'tzinfo', None):
d = d.replace(tzinfo=tz)
else:
d = d.replace(tzinfo=dt.tzinfo)
return to_timezone(d, tzinfo)
def to_local(dt, tzinfo=None):
tz = pick_timezone(tzinfo, __local_timezone__)
return to_datetime(dt, tzinfo=tz)
def to_string(dt, microsecond=False, timezone=True):
if isinstance(dt, datetime):
format = '%Y-%m-%d %H:%M:%S'
if microsecond:
format += '.%f'
if timezone:
format += ' %Z'
return dt.strftime(format).rstrip()
elif isinstance(dt, date):
return dt.strftime('%Y-%m-%d')
elif isinstance(dt, time_):
format = '%H:%M:%S'
if microsecond:
format += '.%f'
return dt.strftime(format)
re_time = re.compile(r'(\d+)([s|ms|h|m])')
def parse_time(t):
if isinstance(t, (str, unicode)):
b = re_time.match(t)
if b:
v, unit = int(b.group(1)), b.group(2)
if unit == 's':
return v*1000
elif unit == 'm':
return v*60*1000
elif unit == 'h':
return v*60*60*1000
else:
return v
else:
raise TimeFormatError(t)
elif isinstance(t, (int, long)):
return t
else:
raise TimeFormatError(t)
#if __name__ == '__main__':
# GMT8 = timezone('GMT +8')
# d = to_datetime('2011-9-13 20:14:15', tzinfo=GMT8)
# print repr(d)
# set_timezone(UTC)
# print repr(to_datetime(d))
# set_local_timezone('GMT +8')
# print get_local_timezone()
# print repr(to_local(d))