55Sunday as the last (the European convention). Use setfirstweekday() to
66set the first day of the week (0=Monday, 6=Sunday)."""
77
8- # Revision 2: uses functions from built-in time module
9-
10- # Import functions and variables from time module
11- from time import localtime , mktime , strftime
8+ import datetime
129
1310__all__ = ["error" ,"setfirstweekday" ,"firstweekday" ,"isleap" ,
1411 "leapdays" ,"weekday" ,"monthrange" ,"monthcalendar" ,
@@ -35,7 +32,7 @@ def __init__(self, format):
3532 self .format = format
3633
3734 def __getitem__ (self , i ):
38- data = [strftime ( self . format , (2001 , j , 1 , 12 , 0 , 0 , 1 , 1 , 0 ) )
35+ data = [datetime . date (2001 , j , 1 ). strftime ( self . format )
3936 for j in range (1 , 13 )]
4037 data .insert (0 , "" )
4138 return data [i ]
@@ -49,7 +46,7 @@ def __init__(self, format):
4946
5047 def __getitem__ (self , i ):
5148 # January 1, 2001, was a Monday.
52- data = [strftime ( self . format , (2001 , 1 , j + 1 , 12 , 0 , 0 , j , j + 1 , 0 ) )
49+ data = [datetime . date (2001 , 1 , j + 1 ). strftime ( self . format )
5350 for j in range (7 )]
5451 return data [i ]
5552
@@ -89,14 +86,12 @@ def leapdays(y1, y2):
8986 Assume y1 <= y2."""
9087 y1 -= 1
9188 y2 -= 1
92- return (y2 / 4 - y1 / 4 ) - (y2 / 100 - y1 / 100 ) + (y2 / 400 - y1 / 400 )
89+ return (y2 // 4 - y1 // 4 ) - (y2 // 100 - y1 // 100 ) + (y2 // 400 - y1 / /400 )
9390
9491def weekday (year , month , day ):
9592 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
9693 day (1-31)."""
97- secs = mktime ((year , month , day , 0 , 0 , 0 , 0 , 0 , 0 ))
98- tuple = localtime (secs )
99- return tuple [6 ]
94+ return datetime .date (year , month , day ).weekday ()
10095
10196def monthrange (year , month ):
10297 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
@@ -213,17 +208,12 @@ def calendar(year, w=0, l=0, c=_spacing):
213208 return s [:- l ] + '\n '
214209
215210EPOCH = 1970
211+ _EPOCH_ORD = datetime .date (EPOCH , 1 , 1 ).toordinal ()
212+
216213def timegm (tuple ):
217214 """Unrelated but handy function to calculate Unix timestamp from GMT."""
218215 year , month , day , hour , minute , second = tuple [:6 ]
219- assert year >= EPOCH
220- assert 1 <= month <= 12
221- days = 365 * (year - EPOCH ) + leapdays (EPOCH , year )
222- for i in range (1 , month ):
223- days = days + mdays [i ]
224- if month > 2 and isleap (year ):
225- days = days + 1
226- days = days + day - 1
216+ days = datetime .date (year , month , day ).toordinal () - _EPOCH_ORD
227217 hours = days * 24 + hour
228218 minutes = hours * 60 + minute
229219 seconds = minutes * 60 + second
0 commit comments