File: DateTime.py

package info (click to toggle)
python-mxdatetime 1.0.1-1
  • links: PTS
  • area: main
  • in suites: slink
  • size: 424 kB
  • ctags: 670
  • sloc: ansic: 2,721; python: 1,387; makefile: 44; sh: 19
file content (458 lines) | stat: -rw-r--r-- 12,780 bytes parent folder | download
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
""" Python part of the low-level DateTime[Delta] type implementation.

    (c) 1998, Copyright Marc-Andre Lemburg; All Rights Reserved.
    See the documentation for further information on copyrights,
    or contact the author (mal@lemburg.com).
"""
# Import C extension module
from mxDateTime import *
from mxDateTime import __version__

# Singletons
oneSecond = DateTimeDelta(0,0,0,1)
oneMinute = DateTimeDelta(0,0,1)
oneHour = DateTimeDelta(0,1)
oneDay = DateTimeDelta(1)
oneWeek = DateTimeDelta(7)
Epoch = DateTimeFromAbsDateTime(1,0)

# Shortcuts for pickle (reduces the pickle's length)
def _DT(absdate,abstime):
    return DateTimeFromAbsDateTime(absdate,abstime)
def _DTD(seconds):
    return DateTimeDeltaFromSeconds(seconds)

# Module init
class modinit:

    global _time,_string
    import time,string
    _time = time
    _string = string

    ### Register the two types
    import copy_reg
    def pickle_DateTime(d):
	return _DT,(d.absdate,d.abstime)
    def pickle_DateTimeDelta(d):
	return _DTD,(d.seconds,)
    copy_reg.pickle(DateTimeType,
		    pickle_DateTime,
		    _DT)
    copy_reg.pickle(DateTimeDeltaType,
		    pickle_DateTimeDelta,
		    _DTD)

del modinit

# Aliases and functions to make 'from DateTime import *' work much
# like 'from time import *'

def localtime(ticks=None,
	      # Locals:
	      time=_time.time,float=float,localtime=_time.localtime,
	      round=round,int=int,DateTime=DateTime):

    """localtime(ticks=None)

    Construct a DateTime instance using local time from ticks.
    If ticks are not given, it defaults to the current time.
    The result is similar to time.localtime(). Fractions of a
    second are rounded to the nearest micro-second."""

    if ticks is None:
	ticks = time()
    else:
	ticks = float(ticks)
    Y,M,D,h,m,s = localtime(ticks)[:6]
    s = round(s + (ticks - int(ticks)),6)
    return DateTime(Y,M,D,h,m,s)

def gmtime(ticks=None,
	   # Locals:
	   time=_time.time,float=float,gmtime=_time.gmtime,
	   round=round,int=int,DateTime=DateTime):

    """gmtime(ticks=None)

    Construct a DateTime instance using UTC time from ticks.
    If ticks are not given, it defaults to the current time.
    The result is similar to time.gmtime(). Fractions of a
    second are rounded to the nearest micro-second."""

    if ticks is None:
	ticks = time()
    else:
	ticks = float(ticks)
    Y,M,D,h,m,s = gmtime(ticks)[:6]
    s = round(s + (ticks - int(ticks)),6)
    return DateTime(Y,M,D,h,m,s)

def mktime(year,month,day,hour,minute,second,dow,doy,dst,
	   # Locals:
	   DateTime=DateTime):

    """mktime(year,month,day,hour,minute,second,dow,doy,dst)

    Alias for DateTime that excepts additional arguments to be
    call compatible with time.mktime(). Note that the arguments dow,doy
    and dst are not used in any way."""

    return DateTime(year,month,day,hour,minute,second)

def ctime(datetime):

    """ctime(datetime)

    Returns a string representation of the given DateTime instance
    using the current locale's default settings."""

    return datetime.strftime('%c')

def today(hour=0,minute=0,second=0.0,
	  # Locals:
	  localtime=_time.localtime,time=_time.time,DateTime=DateTime):

    """today(hour=0,minute=0,second=0.0)

    Returns a DateTime instance for today (in local time) at the
    given time (defaults to midnight)."""

    Y,M,D = localtime(time())[:3]
    return DateTime(Y,M,D,hour,minute,second)

def TimeDelta(hours=0.0,minutes=0.0,seconds=0.0,
	      # Locals:
	      DateTimeDelta=DateTimeDelta):

    """TimeDelta(hours=0.0,minutes=0.0,seconds=0.0)

    Returns a DateTimeDelta-object reflecting the given
    time delta. Seconds can be given as float to indicate fractions."""

    return DateTimeDelta(0,hours,minutes,seconds)

# Choose the implementation for gmticks()... the timegm() C API
# is preferred over the mktime() approach (which may fail on some
# platforms).

if hasattr(Epoch,'gmticks'):

    def gmticks(datetime):

	"""gmticks(datetime)

	Returns a ticks value based on the values stored in
	datetime under the assumption that they are given
	in UTC, rather than local time."""

	return datetime.gmticks()

    def tz_offset(datetime,
		  # Locals:
		  oneSecond=oneSecond):

	"""tz_offset(datetime)

	Returns a DateTimeDelta instance representing the UTC offset
	for datetime assuming that the stored values refer to local
	time. If you subtract this value from datetime, you'll get UTC
	time."""

	return (datetime.gmticks() - datetime.ticks())*oneSecond

    # Note: The method used for calculating the tz offset may fail
    # near the DST switching time. I haven't put much thought into
    # this yet, but some experiments show that it continues to
    # work even during the switching periods. This is, of course, no proof.

else:

    def gmticks(datetime):

	"""gmticks(datetime)

	Returns a ticks value based on the values stored in
	datetime under the assumption that they are given
	in UTC, rather than local time."""
	try:
	    return datetime.ticks(_time.timezone,0)
	except SystemError:
	    raise SystemError,'gmticks() is not supported on this platform'

    def tz_offset(datetime,
		  # Locals:
		  oneSecond=oneSecond):

	"""tz_offset(datetime)

	Returns a DateTimeDelta instance representing the UTC offset
	for datetime assuming that the stored values refer to local
	time. If you subtract this value from datetime, you'll get UTC
	time."""

	local = datetime.ticks()
	try:
	    gmt = datetime.ticks(_time.timezone,0)
	except SystemError:
	    raise SystemError,'tz_offset() is not supported on this platform'
	return (gmt - local)*oneSecond

def gm2local(datetime):

    """ Convert a DateTime instance holding UTC time to a DateTime
        instance using local time.
    """
    return localtime(gmticks(datetime))

def local2gm(datetime):

    """ Convert a DateTime instance holding local time to a DateTime
        instance using UTC time.
    """
    return gmtime(datetime.ticks())

###

class RelativeDateTime:

    """RelativeDateTime(years=0,months=0,days=0,year=0,month=0,day=0,
		      hours=0,minutes=0,seconds=0,
		      hour=None,minute=None,second=None)

       Returns a RelativeDateTime instance for the specified relative
       time. The constructor handles keywords, so you'll only have to
       give those parameters which should be changed when you add the
       relative to an absolute DateTime instance. Absolute values passed
       to the constructor will override delta values of the same type.

       Adding RelativeDateTime instances is supported with the
       following rules: deltas will be added together, right side
       absolute values override left side ones.

       Adding RelativeDateTime instances to DateTime instances will
       return DateTime instances with the appropriate calculations
       applied, e.g. to get a DateTime instance for the first of next
       month, you'd call now()+RelativeDateTime(months=+1,day=01).

    """
    years = 0
    months = 0
    days = 0
    year = 0
    month = 0
    day = 0
    hours = 0
    minutes = 0
    seconds = 0
    hour = None
    minute = None
    second = None

    def __init__(self,years=0,months=0,days=0,year=0,month=0,day=0,
		      hours=0,minutes=0,seconds=0,
		      hour=None,minute=None,second=None):
	
	self.years = years
	self.months = months
	self.days = days
	self.year = year
	self.month = month
	self.day = day
	self.hours = hours
	self.minutes = minutes
	self.seconds = seconds
	self.hour = hour
	self.minute = minute
	self.second = second

    def __add__(self,other):

	if isinstance(other,RelativeDateTime):
	    # RelativeDateTime (self) + RelativeDateTime (other)

	    r = RelativeDateTime()
	    # date deltas
	    r.years = self.years + other.years
	    r.months = self.months + other.months
	    r.days = self.days + other.days
	    # absolute entries of other override those in self, if given
	    r.year = other.year or self.year
	    r.month = other.month or self.month
	    r.day = other.day or self.day
	    # time deltas
	    r.hours = self.hours + other.hours
	    r.minutes = self.minutes + other.minutes
	    r.seconds = self.seconds + other.seconds
	    # absolute entries of other override those in self, if given
	    r.hour = other.hour or self.hour
	    r.minute = other.minute or self.minute
	    r.second = other.second or self.second
	    return r

	else:
	    raise TypeError,"can't add the two types"

    def __radd__(self,other,
		 # Locals:
		 None=None,isinstance=isinstance,DateTime=DateTime):

	if isinstance(other,DateTimeType):
	    # DateTime (other) + RelativeDateTime (self)

	    # date
	    year = self.year or (other.year + self.years)
	    month = self.month or (other.month + self.months)
	    day = self.day or (other.day + self.days)
	    # time
	    hour = self.hour
	    if hour is None:
		hour = other.hour + self.hours
	    minute = self.minute
	    if minute is None:
		minute = other.minute + self.minutes
	    second = self.second
	    if second is None:
		second = other.second + self.seconds

	    #print 'first try:',year, month, day, hour, minute, second
	    if month > 0 and day > 0:
		try:
		    return DateTime(year, month, day, hour, minute, second)
		except RangeError:
		    pass
	    # Refit into proper ranges:
	    if month < 1 or month > 12:
		month = month - 1
		year = year + month / 12
		month = month % 12 + 1
	    #print 'second try:',year, month, day, hour, minute, second
	    return DateTime(year, month, 1) + \
		   DateTimeDelta(day-1,hour,minute,second)
	else:
	    raise TypeError,"can't add the two types"

    def __sub__(self,other):

	if isinstance(other,RelativeDateTime):
	    # RelativeDateTime (self) - RelativeDateTime (other)

	    r = RelativeDateTime()
	    # date deltas
	    r.years = self.years - other.years
	    r.months = self.months - other.months
	    r.days = self.days - other.days
	    # absolute entries of other override those in self, if given
	    r.year = other.year or self.year
	    r.month = other.month or self.month
	    r.day = other.day or self.day
	    # time deltas
	    r.hours = self.hours - other.hours
	    r.minutes = self.minutes - other.minutes
	    r.seconds = self.seconds - other.seconds
	    # absolute entries of other override those in self, if given
	    r.hour = other.hour or self.hour
	    r.minute = other.minute or self.minute
	    r.second = other.second or self.second

	    return r

	else:
	    raise TypeError,"can't subtract the two types"

    def __rsub__(self,other,
		 # Locals:
		 None=None,isinstance=isinstance,DateTime=DateTime):

	if isinstance(other,DateTimeType):
	    # DateTime (other) - RelativeDateTime (self)

	    # date
	    year = self.year or (other.year - self.years)
	    month = self.month or (other.month - self.months)
	    day = self.day or (other.day - self.days)

	    # time
	    hour = self.hour
	    if hour is None:
		hour = other.hour - self.hours
	    minute = self.minute
	    if minute is None:
		minute = other.minute - self.minutes
	    second = self.second
	    if second is None:
		second = other.second - self.seconds

	    #print 'first try:',year, month, day, hour, minute, second
	    if month > 0 and day > 0:
		try:
		    return DateTime(year, month, day, hour, minute, second)
		except RangeError:
		    pass
	    # Refit into proper ranges:
	    if month < 1 or month > 12:
		month = month - 1
		year = year + month / 12
		month = month % 12 + 1
	    #print 'second try:',year, month, day, hour, minute, second
	    return DateTime(year, month, 1) + \
		   DateTimeDelta(day-1,hour,minute,second)
	else:
	    raise TypeError,"can't subtract the two types"

    def __str__(self,

		join=_string.join):

	l = []
	append = l.append
	if self.year:
	    append('%04i-' % self.year)
	elif self.years:
	    append('(%0+5i)-' % self.years)
	else:
	    append('YYYY-')
	if self.month:
	    append('%02i-' % self.month)
	elif self.months:
	    append('(%0+3i)-' % self.months)
	else:
	    append('MM-')
	if self.day:
	    append('%02i ' % self.day)
	elif self.days:
	    append('(%0+3i) ' % self.days)
	else:
	    append('DD ')
	append(' ')
	if self.hour is not None:
	    append('%02i:' % self.hour)
	elif self.hours:
	    append('(%0+3i):' % self.hours)
	else:
	    append('HH:')
	if self.minute is not None:
	    append('%02i:' % self.minute)
	elif self.minutes:
	    append('(%0+3i):' % self.minutes)
	else:
	    append('MM:')
	if self.second is not None:
	    append('%02i' % self.second)
	elif self.seconds:
	    append('(%0+3i)' % self.seconds)
	else:
	    append('SS')
	return join(l,'')

# Aliases
utctime = gmtime
utcticks = gmticks
utc2local = gm2local
local2utc = local2gm
DateTimeFromTicks = localtime
now = localtime
Date = DateTime
Time = TimeDelta
Timestamp = DateTime
RelativeDate = RelativeDateTime