1 """Parse a timezone specification."""
4 # XXX Only the typical form "XXXhhYYY;ddd/hh,ddd/hh" is currently supported.
6 tzpat
= ('^([A-Z][A-Z][A-Z])([-+]?[0-9]+)([A-Z][A-Z][A-Z]);'
7 '([0-9]+)/([0-9]+),([0-9]+)/([0-9]+)$')
12 """Given a timezone spec, return a tuple of information
13 (tzname, delta, dstname, daystart, hourstart, dayend, hourend),
14 where 'tzname' is the name of the timezone, 'delta' is the offset
15 in hours from GMT, 'dstname' is the name of the daylight-saving
16 timezone, and 'daystart'/'hourstart' and 'dayend'/'hourend'
17 specify the starting and ending points for daylight saving time."""
21 tzprog
= re
.compile(tzpat
)
22 match
= tzprog
.match(tzstr
)
24 raise ValueError, 'not the TZ syntax I understand'
27 subs
.append(match
.group(i
))
28 for i
in (1, 3, 4, 5, 6):
29 subs
[i
] = eval(subs
[i
])
30 [tzname
, delta
, dstname
, daystart
, hourstart
, dayend
, hourend
] = subs
31 return (tzname
, delta
, dstname
, daystart
, hourstart
, dayend
, hourend
)
33 def tzlocaltime(secs
, params
):
34 """Given a Unix time in seconds and a tuple of information about
35 a timezone as returned by tzparse(), return the local time in the
36 form (year, month, day, hour, min, sec, yday, wday, tzname)."""
38 (tzname
, delta
, dstname
, daystart
, hourstart
, dayend
, hourend
) = params
39 year
, month
, days
, hours
, mins
, secs
, yday
, wday
, isdst
= \
40 time
.gmtime(secs
- delta
*3600)
41 if (daystart
, hourstart
) <= (yday
+1, hours
) < (dayend
, hourend
):
44 return year
, month
, days
, hours
, mins
, secs
, yday
, wday
, tzname
47 """Determine the current timezone from the "TZ" environment variable."""
48 global tzparams
, timezone
, altzone
, daylight
, tzname
50 tzstr
= os
.environ
['TZ']
51 tzparams
= tzparse(tzstr
)
52 timezone
= tzparams
[1] * 3600
53 altzone
= timezone
- 3600
55 tzname
= tzparams
[0], tzparams
[2]
58 """Return true if daylight-saving time is in effect for the given
59 Unix time in the current timezone."""
61 (tzname
, delta
, dstname
, daystart
, hourstart
, dayend
, hourend
) = \
63 year
, month
, days
, hours
, mins
, secs
, yday
, wday
, isdst
= \
64 time
.gmtime(secs
- delta
*3600)
65 return (daystart
, hourstart
) <= (yday
+1, hours
) < (dayend
, hourend
)
70 """Get the local time in the current timezone."""
71 return tzlocaltime(secs
, tzparams
)
74 from time
import asctime
, gmtime
79 print 'now =', now
, '=', asctime(tm
), x
[-1]
80 now
= now
- now
% (24*3600)
81 if sys
.argv
[1:]: now
= now
+ eval(sys
.argv
[1])
84 print 'gmtime =', now
, '=', asctime(tm
), 'yday =', x
[-2]
85 jan1
= now
- x
[-2]*24*3600
88 print 'jan1 =', jan1
, '=', asctime(tm
), x
[-1]
89 for d
in range(85, 95) + range(265, 275):
93 print 'd =', d
, 't =', t
, '=', asctime(tm
), x
[-1]