Function to use several blocks of if:elif:else:
that all take slightly different conditional statements. I'm trying to format integers into a 2 digit string, adding a leading 0
for single digits. It is working great, but there has to be DRY way of doing the same thing. Also, the timezone formatting is a bit of a mess. After struggling to come up with a more elegant solution, I just went with what was obvious and working.
def rfc_3339_str(minutes = 0, year = 1999, month = 1, date = 1, secs = 0, time_zone = 0):
'''Takes minutes and builds RFC 3339 timeDate string.
yyyy-mm-ddTHH:MM:ss[.mmm][+/-HH:MM]. Does not support milliseconds.
All params optional. Timezone format is number in range
[-12:12] (hours only). All numbers expect integers.
Minutes > 1439 (23 hours 59 minutes) wrap around to zero,.
Date defaults to 1/1/1999. Supported years 1000-2035 CE. Date allows
range 0-31 inclusive for all months. Negative times are not supported.
Incorrect params return error description'''
plus = '+'
minus = '-'
date_time_split = 'T'
date_split = '-'
time_split = ':'
time_zone_mins = ':00'
MAX_MINUTES = 1440
yyyy = None
mm = None
dd = None
HH = None
MM = None
SS = None
zone_sign = plus
zz = None
#validate inputs
if 1000 > year > 2035:
return 'year_out_of_range'
else:
yyyy = str(year)
if month in range(1,10):
mm = '0' + str(month)
elif month in range(10,13):
mm = str(month)
else:
return 'month_out_of_range'
if date in range(1, 10):
dd = '0' + str(date)
elif date in range(10, 32):
dd = str(date)
else:
return 'date_out_of_range'
if minutes < 0:
return 'minutes_out_of_range'
while minutes > MAX_MINUTES:
minutes = minutes - MAX_MINUTES
hours_int = int(minutes / 60)
mins_int = int(minutes % 60)
if hours_int in range(0,10):
HH = '0' + str(hours_int)
elif hours_int in range(10, 100):
HH = str(hours_int)
else:
return 'hours_out_of_range'
if mins_int in range(0,10):
MM = '0' + str(mins_int)
elif mins_int in range(10,60):
MM = str(mins_int)
else:
return 'minutes_out_of_range'
if secs in range(0, 10):
ss = '0' + str(secs)
elif secs in range(10,60):
ss = str(secs)
else:
return 'seconds_out_of_range'
small = False
positive = False
if time_zone in range(-9, 10):
small = True
if time_zone in range(-12,0):
positive = False
if time_zone in range(0, 13):
positive = True
if small:
zz = '0'
if positive:
zz = plus + zz + str(time_zone)
if not positive:
zz = minus + zz + str(abs(time_zone))
else:
zz = plus + '00'
print(yyyy + date_split + mm + date_split + dd +
date_time_split + HH + time_split +
MM + time_split + ss +
zz + time_zone_mins)
datetime
as an argument. – georg 2 days ago