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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
|
from rpython.rtyper.tool import rffi_platform as platform
from rpython.rtyper.lltypesystem import rffi
from pypy.interpreter.error import OperationError, operationerrfmt
from pypy.interpreter.gateway import unwrap_spec
from rpython.rtyper.lltypesystem import lltype
from rpython.rlib.rarithmetic import ovfcheck_float_to_int, intmask
from rpython.rlib import rposix
from rpython.translator.tool.cbuild import ExternalCompilationInfo
import os
import sys
import time as pytime
_POSIX = os.name == "posix"
_WIN = os.name == "nt"
_CYGWIN = sys.platform == "cygwin"
_time_zones = []
if _CYGWIN:
_time_zones = ["GMT-12", "GMT-11", "GMT-10", "GMT-9", "GMT-8", "GMT-7",
"GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1",
"GMT", "GMT+1", "GMT+2", "GMT+3", "GMT+4", "GMT+5",
"GMT+6", "GMT+7", "GMT+8", "GMT+9", "GMT+10", "GMT+11",
"GMT+12", "GMT+13", "GMT+14"]
if _WIN:
# Interruptible sleeps on Windows:
# We install a specific Console Ctrl Handler which sets an 'event'.
# time.sleep() will actually call WaitForSingleObject with the desired
# timeout. On Ctrl-C, the signal handler is called, the event is set,
# and the wait function exits.
from rpython.rlib import rwin32
from pypy.interpreter.error import wrap_windowserror, wrap_oserror
from rpython.rlib import rthread as thread
eci = ExternalCompilationInfo(
includes = ['windows.h'],
post_include_bits = ["BOOL pypy_timemodule_setCtrlHandler(HANDLE event);"],
separate_module_sources=['''
static HANDLE interrupt_event;
static BOOL WINAPI CtrlHandlerRoutine(
DWORD dwCtrlType)
{
SetEvent(interrupt_event);
/* allow other default handlers to be called.
* Default Python handler will setup the
* KeyboardInterrupt exception.
*/
return 0;
}
BOOL pypy_timemodule_setCtrlHandler(HANDLE event)
{
interrupt_event = event;
return SetConsoleCtrlHandler(CtrlHandlerRoutine, TRUE);
}
'''],
export_symbols=['pypy_timemodule_setCtrlHandler'],
)
_setCtrlHandlerRoutine = rffi.llexternal(
'pypy_timemodule_setCtrlHandler',
[rwin32.HANDLE], rwin32.BOOL,
compilation_info=eci)
class GlobalState:
def __init__(self):
self.init()
def init(self):
self.interrupt_event = rwin32.NULL_HANDLE
def startup(self, space):
# Initialize the event handle used to signal Ctrl-C
try:
globalState.interrupt_event = rwin32.CreateEvent(
rffi.NULL, True, False, rffi.NULL)
except WindowsError, e:
raise wrap_windowserror(space, e)
if not _setCtrlHandlerRoutine(globalState.interrupt_event):
raise wrap_windowserror(
space, rwin32.lastWindowsError("SetConsoleCtrlHandler"))
globalState = GlobalState()
class State:
def __init__(self, space):
self.main_thread = 0
def _cleanup_(self):
self.main_thread = 0
globalState.init()
def startup(self, space):
self.main_thread = thread.get_ident()
globalState.startup(space)
def get_interrupt_event(self):
return globalState.interrupt_event
_includes = ["time.h"]
if _POSIX:
_includes.append('sys/time.h')
class CConfig:
_compilation_info_ = ExternalCompilationInfo(
includes = _includes
)
CLOCKS_PER_SEC = platform.ConstantInteger("CLOCKS_PER_SEC")
clock_t = platform.SimpleType("clock_t", rffi.ULONG)
has_gettimeofday = platform.Has('gettimeofday')
if _POSIX:
calling_conv = 'c'
CConfig.timeval = platform.Struct("struct timeval",
[("tv_sec", rffi.INT),
("tv_usec", rffi.INT)])
if _CYGWIN:
CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
("tm_min", rffi.INT), ("tm_hour", rffi.INT), ("tm_mday", rffi.INT),
("tm_mon", rffi.INT), ("tm_year", rffi.INT), ("tm_wday", rffi.INT),
("tm_yday", rffi.INT), ("tm_isdst", rffi.INT)])
else:
CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
("tm_min", rffi.INT), ("tm_hour", rffi.INT), ("tm_mday", rffi.INT),
("tm_mon", rffi.INT), ("tm_year", rffi.INT), ("tm_wday", rffi.INT),
("tm_yday", rffi.INT), ("tm_isdst", rffi.INT), ("tm_gmtoff", rffi.LONG),
("tm_zone", rffi.CCHARP)])
elif _WIN:
calling_conv = 'win'
CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
("tm_min", rffi.INT), ("tm_hour", rffi.INT), ("tm_mday", rffi.INT),
("tm_mon", rffi.INT), ("tm_year", rffi.INT), ("tm_wday", rffi.INT),
("tm_yday", rffi.INT), ("tm_isdst", rffi.INT)])
class cConfig:
pass
for k, v in platform.configure(CConfig).items():
setattr(cConfig, k, v)
cConfig.tm.__name__ = "_tm"
def external(name, args, result, eci=CConfig._compilation_info_):
if _WIN and rffi.sizeof(rffi.TIME_T) == 8:
# Recent Microsoft compilers use 64bit time_t and
# the corresponding functions are named differently
if (rffi.TIME_T in args or rffi.TIME_TP in args
or result in (rffi.TIME_T, rffi.TIME_TP)):
name = '_' + name + '64'
return rffi.llexternal(name, args, result,
compilation_info=eci,
calling_conv=calling_conv,
threadsafe=False)
if _POSIX:
cConfig.timeval.__name__ = "_timeval"
timeval = cConfig.timeval
CLOCKS_PER_SEC = cConfig.CLOCKS_PER_SEC
clock_t = cConfig.clock_t
tm = cConfig.tm
glob_buf = lltype.malloc(tm, flavor='raw', zero=True, immortal=True)
if cConfig.has_gettimeofday:
c_gettimeofday = external('gettimeofday', [rffi.VOIDP, rffi.VOIDP], rffi.INT)
TM_P = lltype.Ptr(tm)
c_clock = external('clock', [rffi.TIME_TP], clock_t)
c_time = external('time', [rffi.TIME_TP], rffi.TIME_T)
c_ctime = external('ctime', [rffi.TIME_TP], rffi.CCHARP)
c_gmtime = external('gmtime', [rffi.TIME_TP], TM_P)
c_mktime = external('mktime', [TM_P], rffi.TIME_T)
c_asctime = external('asctime', [TM_P], rffi.CCHARP)
c_localtime = external('localtime', [rffi.TIME_TP], TM_P)
if _POSIX:
c_tzset = external('tzset', [], lltype.Void)
if _WIN:
win_eci = ExternalCompilationInfo(
includes = ["time.h"],
post_include_bits = ["long pypy_get_timezone();",
"int pypy_get_daylight();",
"char** pypy_get_tzname();"],
separate_module_sources = ["""
long pypy_get_timezone() { return timezone; }
int pypy_get_daylight() { return daylight; }
char** pypy_get_tzname() { return tzname; }
"""],
export_symbols = [
'_tzset', 'pypy_get_timezone', 'pypy_get_daylight', 'pypy_get_tzname'],
)
# Ensure sure that we use _tzset() and timezone from the same C Runtime.
c_tzset = external('_tzset', [], lltype.Void, win_eci)
c_get_timezone = external('pypy_get_timezone', [], rffi.LONG, win_eci)
c_get_daylight = external('pypy_get_daylight', [], rffi.INT, win_eci)
c_get_tzname = external('pypy_get_tzname', [], rffi.CCHARPP, win_eci)
c_strftime = external('strftime', [rffi.CCHARP, rffi.SIZE_T, rffi.CCHARP, TM_P],
rffi.SIZE_T)
def _init_accept2dyear(space):
if os.environ.get("PYTHONY2K"):
accept2dyear = 0
else:
accept2dyear = 1
_set_module_object(space, "accept2dyear", space.wrap(accept2dyear))
def _init_timezone(space):
timezone = daylight = altzone = 0
tzname = ["", ""]
if _WIN:
c_tzset()
timezone = c_get_timezone()
altzone = timezone - 3600
daylight = c_get_daylight()
tzname_ptr = c_get_tzname()
tzname = rffi.charp2str(tzname_ptr[0]), rffi.charp2str(tzname_ptr[1])
if _POSIX:
if _CYGWIN:
YEAR = (365 * 24 + 6) * 3600
# about January 11th
t = (((c_time(lltype.nullptr(rffi.TIME_TP.TO))) / YEAR) * YEAR + 10 * 24 * 3600)
# we cannot have reference to stack variable, put it on the heap
t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
t_ref[0] = rffi.cast(rffi.TIME_T, t)
p = c_localtime(t_ref)
q = c_gmtime(t_ref)
janzone = (p.c_tm_hour + 24 * p.c_tm_mday) - (q.c_tm_hour + 24 * q.c_tm_mday)
if janzone < -12:
janname = " "
elif janzone > 14:
janname = " "
else:
janname = _time_zones[janzone - 12]
janzone = janzone * 3600
# about July 11th
tt = t + YEAR / 2
t_ref[0] = rffi.cast(rffi.TIME_T, tt)
p = c_localtime(t_ref)
q = c_gmtime(t_ref)
julyzone = (p.c_tm_hour + 24 * p.c_tm_mday) - (q.c_tm_hour + 24 * q.c_tm_mday)
if julyzone < -12:
julyname = " "
elif julyzone > 14:
julyname = " "
else:
julyname = _time_zones[julyzone - 12]
julyzone = julyzone * 3600
lltype.free(t_ref, flavor='raw')
if janzone < julyzone:
# DST is reversed in the southern hemisphere
timezone = julyzone
altzone = janzone
daylight = int(janzone != julyzone)
tzname = [julyname, janname]
else:
timezone = janzone
altzone = julyzone
daylight = int(janzone != julyzone)
tzname = [janname, julyname]
else:
YEAR = (365 * 24 + 6) * 3600
t = (((c_time(lltype.nullptr(rffi.TIME_TP.TO))) / YEAR) * YEAR)
# we cannot have reference to stack variable, put it on the heap
t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
t_ref[0] = rffi.cast(rffi.TIME_T, t)
p = c_localtime(t_ref)
janzone = -p.c_tm_gmtoff
tm_zone = rffi.charp2str(p.c_tm_zone)
janname = [" ", tm_zone][bool(tm_zone)]
tt = t + YEAR / 2
t_ref[0] = rffi.cast(rffi.TIME_T, tt)
p = c_localtime(t_ref)
lltype.free(t_ref, flavor='raw')
tm_zone = rffi.charp2str(p.c_tm_zone)
julyzone = -p.c_tm_gmtoff
julyname = [" ", tm_zone][bool(tm_zone)]
if janzone < julyzone:
# DST is reversed in the southern hemisphere
timezone = julyzone
altzone = janzone
daylight = int(janzone != julyzone)
tzname = [julyname, janname]
else:
timezone = janzone
altzone = julyzone
daylight = int(janzone != julyzone)
tzname = [janname, julyname]
_set_module_object(space, "timezone", space.wrap(timezone))
_set_module_object(space, 'daylight', space.wrap(daylight))
tzname_w = [space.wrap(tzname[0]), space.wrap(tzname[1])]
_set_module_object(space, 'tzname', space.newtuple(tzname_w))
_set_module_object(space, 'altzone', space.wrap(altzone))
def _get_error_msg():
errno = rposix.get_errno()
return os.strerror(errno)
if sys.platform != 'win32':
@unwrap_spec(secs=float)
def sleep(space, secs):
if secs < 0:
raise OperationError(space.w_IOError,
space.wrap("Invalid argument: negative time in sleep"))
pytime.sleep(secs)
else:
from rpython.rlib import rwin32
from errno import EINTR
def _simple_sleep(space, secs, interruptible):
if secs == 0.0 or not interruptible:
pytime.sleep(secs)
else:
millisecs = int(secs * 1000)
interrupt_event = space.fromcache(State).get_interrupt_event()
rwin32.ResetEvent(interrupt_event)
rc = rwin32.WaitForSingleObject(interrupt_event, millisecs)
if rc == rwin32.WAIT_OBJECT_0:
# Yield to make sure real Python signal handler
# called.
pytime.sleep(0.001)
raise wrap_oserror(space,
OSError(EINTR, "sleep() interrupted"))
@unwrap_spec(secs=float)
def sleep(space, secs):
if secs < 0:
raise OperationError(space.w_IOError,
space.wrap("Invalid argument: negative time in sleep"))
# as decreed by Guido, only the main thread can be
# interrupted.
main_thread = space.fromcache(State).main_thread
interruptible = (main_thread == thread.get_ident())
MAX = sys.maxint / 1000.0 # > 24 days
while secs > MAX:
_simple_sleep(space, MAX, interruptible)
secs -= MAX
_simple_sleep(space, secs, interruptible)
def _get_module_object(space, obj_name):
w_module = space.getbuiltinmodule('time')
w_obj = space.getattr(w_module, space.wrap(obj_name))
return w_obj
def _set_module_object(space, obj_name, w_obj_value):
w_module = space.getbuiltinmodule('time')
space.setattr(w_module, space.wrap(obj_name), w_obj_value)
def _get_inttime(space, w_seconds):
# w_seconds can be a wrapped None (it will be automatically wrapped
# in the callers, so we never get a real None here).
if space.is_none(w_seconds):
seconds = pytime.time()
else:
seconds = space.float_w(w_seconds)
try:
seconds = ovfcheck_float_to_int(seconds)
t = rffi.r_time_t(seconds)
if rffi.cast(lltype.Signed, t) != seconds:
raise OverflowError
except OverflowError:
raise OperationError(space.w_ValueError,
space.wrap("time argument too large"))
return t
def _tm_to_tuple(space, t):
time_tuple = [
space.wrap(rffi.getintfield(t, 'c_tm_year') + 1900),
space.wrap(rffi.getintfield(t, 'c_tm_mon') + 1), # want january == 1
space.wrap(rffi.getintfield(t, 'c_tm_mday')),
space.wrap(rffi.getintfield(t, 'c_tm_hour')),
space.wrap(rffi.getintfield(t, 'c_tm_min')),
space.wrap(rffi.getintfield(t, 'c_tm_sec')),
space.wrap((rffi.getintfield(t, 'c_tm_wday') + 6) % 7), # want monday == 0
space.wrap(rffi.getintfield(t, 'c_tm_yday') + 1), # want january, 1 == 1
space.wrap(rffi.getintfield(t, 'c_tm_isdst'))]
w_struct_time = _get_module_object(space, 'struct_time')
w_time_tuple = space.newtuple(time_tuple)
return space.call_function(w_struct_time, w_time_tuple)
def _gettmarg(space, w_tup, allowNone=True):
if space.is_none(w_tup):
if not allowNone:
raise OperationError(space.w_TypeError,
space.wrap("tuple expected"))
# default to the current local time
tt = rffi.r_time_t(int(pytime.time()))
t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
t_ref[0] = tt
pbuf = c_localtime(t_ref)
lltype.free(t_ref, flavor='raw')
if not pbuf:
raise OperationError(space.w_ValueError,
space.wrap(_get_error_msg()))
return pbuf
tup_w = space.fixedview(w_tup)
if len(tup_w) != 9:
raise operationerrfmt(space.w_TypeError,
"argument must be sequence of "
"length 9, not %d", len(tup_w))
y = space.int_w(tup_w[0])
tm_mon = space.int_w(tup_w[1])
if tm_mon == 0:
tm_mon = 1
tm_mday = space.int_w(tup_w[2])
if tm_mday == 0:
tm_mday = 1
tm_yday = space.int_w(tup_w[7])
if tm_yday == 0:
tm_yday = 1
rffi.setintfield(glob_buf, 'c_tm_mon', tm_mon)
rffi.setintfield(glob_buf, 'c_tm_mday', tm_mday)
rffi.setintfield(glob_buf, 'c_tm_hour', space.int_w(tup_w[3]))
rffi.setintfield(glob_buf, 'c_tm_min', space.int_w(tup_w[4]))
rffi.setintfield(glob_buf, 'c_tm_sec', space.int_w(tup_w[5]))
rffi.setintfield(glob_buf, 'c_tm_wday', space.int_w(tup_w[6]))
rffi.setintfield(glob_buf, 'c_tm_yday', tm_yday)
rffi.setintfield(glob_buf, 'c_tm_isdst', space.int_w(tup_w[8]))
if _POSIX:
if _CYGWIN:
pass
else:
# actually never happens, but makes annotator happy
glob_buf.c_tm_zone = lltype.nullptr(rffi.CCHARP.TO)
rffi.setintfield(glob_buf, 'c_tm_gmtoff', 0)
if y < 1900:
w_accept2dyear = _get_module_object(space, "accept2dyear")
accept2dyear = space.int_w(w_accept2dyear)
if not accept2dyear:
raise OperationError(space.w_ValueError,
space.wrap("year >= 1900 required"))
if 69 <= y <= 99:
y += 1900
elif 0 <= y <= 68:
y += 2000
else:
raise OperationError(space.w_ValueError,
space.wrap("year out of range"))
# tm_wday does not need checking of its upper-bound since taking "%
# 7" in gettmarg() automatically restricts the range.
if rffi.getintfield(glob_buf, 'c_tm_wday') < -1:
raise OperationError(space.w_ValueError,
space.wrap("day of week out of range"))
rffi.setintfield(glob_buf, 'c_tm_year', y - 1900)
rffi.setintfield(glob_buf, 'c_tm_mon',
rffi.getintfield(glob_buf, 'c_tm_mon') - 1)
rffi.setintfield(glob_buf, 'c_tm_wday',
(rffi.getintfield(glob_buf, 'c_tm_wday') + 1) % 7)
rffi.setintfield(glob_buf, 'c_tm_yday',
rffi.getintfield(glob_buf, 'c_tm_yday') - 1)
return glob_buf
def time(space):
"""time() -> floating point number
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them."""
secs = pytime.time()
return space.wrap(secs)
if _WIN:
class PCCache:
pass
pccache = PCCache()
pccache.divisor = 0.0
pccache.ctrStart = 0
def clock(space):
"""clock() -> floating point number
Return the CPU time or real time since the start of the process or since
the first call to clock(). This has as much precision as the system
records."""
return space.wrap(pytime.clock())
def ctime(space, w_seconds=None):
"""ctime([seconds]) -> string
Convert a time in seconds since the Epoch to a string in local time.
This is equivalent to asctime(localtime(seconds)). When the time tuple is
not present, current time as returned by localtime() is used."""
seconds = _get_inttime(space, w_seconds)
t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
t_ref[0] = seconds
p = c_ctime(t_ref)
lltype.free(t_ref, flavor='raw')
if not p:
raise OperationError(space.w_ValueError,
space.wrap("unconvertible time"))
return space.wrap(rffi.charp2str(p)[:-1]) # get rid of new line
# by now w_tup is an optional argument (and not *args)
# because of the ext. compiler bugs in handling such arguments (*args, **kwds)
def asctime(space, w_tup=None):
"""asctime([tuple]) -> string
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
When the time tuple is not present, current time as returned by localtime()
is used."""
buf_value = _gettmarg(space, w_tup)
p = c_asctime(buf_value)
if not p:
raise OperationError(space.w_ValueError,
space.wrap("unconvertible time"))
return space.wrap(rffi.charp2str(p)[:-1]) # get rid of new line
def gmtime(space, w_seconds=None):
"""gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,
tm_sec, tm_wday, tm_yday, tm_isdst)
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
GMT). When 'seconds' is not passed in, convert the current time instead.
"""
# rpython does not support that a variable has two incompatible builtins
# as value so we have to duplicate the code. NOT GOOD! see localtime() too
seconds = _get_inttime(space, w_seconds)
t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
t_ref[0] = seconds
p = c_gmtime(t_ref)
lltype.free(t_ref, flavor='raw')
if not p:
raise OperationError(space.w_ValueError, space.wrap(_get_error_msg()))
return _tm_to_tuple(space, p)
def localtime(space, w_seconds=None):
"""localtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,
tm_sec, tm_wday, tm_yday, tm_isdst)
Convert seconds since the Epoch to a time tuple expressing local time.
When 'seconds' is not passed in, convert the current time instead."""
seconds = _get_inttime(space, w_seconds)
t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
t_ref[0] = seconds
p = c_localtime(t_ref)
lltype.free(t_ref, flavor='raw')
if not p:
raise OperationError(space.w_ValueError, space.wrap(_get_error_msg()))
return _tm_to_tuple(space, p)
def mktime(space, w_tup):
"""mktime(tuple) -> floating point number
Convert a time tuple in local time to seconds since the Epoch."""
buf = _gettmarg(space, w_tup, allowNone=False)
rffi.setintfield(buf, "c_tm_wday", -1)
tt = c_mktime(buf)
# A return value of -1 does not necessarily mean an error, but tm_wday
# cannot remain set to -1 if mktime succeeds.
if tt == -1 and rffi.getintfield(buf, "c_tm_wday") == -1:
raise OperationError(space.w_OverflowError,
space.wrap("mktime argument out of range"))
return space.wrap(float(tt))
if _POSIX:
def tzset(space):
"""tzset()
Initialize, or reinitialize, the local timezone to the value stored in
os.environ['TZ']. The TZ environment variable should be specified in
standard Unix timezone format as documented in the tzset man page
(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently
fall back to UTC. If the TZ environment variable is not set, the local
timezone is set to the systems best guess of wallclock time.
Changing the TZ environment variable without calling tzset *may* change
the local timezone used by methods such as localtime, but this behaviour
should not be relied on"""
c_tzset()
# reset timezone, altzone, daylight and tzname
_init_timezone(space)
@unwrap_spec(format=str)
def strftime(space, format, w_tup=None):
"""strftime(format[, tuple]) -> string
Convert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used."""
buf_value = _gettmarg(space, w_tup)
# Checks added to make sure strftime() does not crash Python by
# indexing blindly into some array for a textual representation
# by some bad index (fixes bug #897625).
# No check for year since handled in gettmarg().
if rffi.getintfield(buf_value, 'c_tm_mon') < 0 or rffi.getintfield(buf_value, 'c_tm_mon') > 11:
raise OperationError(space.w_ValueError,
space.wrap("month out of range"))
if rffi.getintfield(buf_value, 'c_tm_mday') < 1 or rffi.getintfield(buf_value, 'c_tm_mday') > 31:
raise OperationError(space.w_ValueError,
space.wrap("day of month out of range"))
if rffi.getintfield(buf_value, 'c_tm_hour') < 0 or rffi.getintfield(buf_value, 'c_tm_hour') > 23:
raise OperationError(space.w_ValueError,
space.wrap("hour out of range"))
if rffi.getintfield(buf_value, 'c_tm_min') < 0 or rffi.getintfield(buf_value, 'c_tm_min') > 59:
raise OperationError(space.w_ValueError,
space.wrap("minute out of range"))
if rffi.getintfield(buf_value, 'c_tm_sec') < 0 or rffi.getintfield(buf_value, 'c_tm_sec') > 61:
raise OperationError(space.w_ValueError,
space.wrap("seconds out of range"))
if rffi.getintfield(buf_value, 'c_tm_yday') < 0 or rffi.getintfield(buf_value, 'c_tm_yday') > 365:
raise OperationError(space.w_ValueError,
space.wrap("day of year out of range"))
if rffi.getintfield(buf_value, 'c_tm_isdst') < -1 or rffi.getintfield(buf_value, 'c_tm_isdst') > 1:
raise OperationError(space.w_ValueError,
space.wrap("daylight savings flag out of range"))
if _WIN:
# check that the format string contains only valid directives
length = len(format)
i = 0
while i < length:
if format[i] == '%':
i += 1
if i < length and format[i] == '#':
# not documented by python
i += 1
if i >= length or format[i] not in "aAbBcdHIjmMpSUwWxXyYzZ%":
raise OperationError(space.w_ValueError,
space.wrap("invalid format string"))
i += 1
i = 1024
while True:
outbuf = lltype.malloc(rffi.CCHARP.TO, i, flavor='raw')
try:
buflen = c_strftime(outbuf, i, format, buf_value)
if buflen > 0 or i >= 256 * len(format):
# if the buffer is 256 times as long as the format,
# it's probably not failing for lack of room!
# More likely, the format yields an empty result,
# e.g. an empty format, or %Z when the timezone
# is unknown.
result = rffi.charp2strn(outbuf, intmask(buflen))
return space.wrap(result)
finally:
lltype.free(outbuf, flavor='raw')
i += i
|