def now_minus_delta_time(delta_time_string):
curr_datetime = datetime.datetime.now(pytz.UTC)
slop = 15 * 60 # 15 minutes of "slop" allowed in determining new backup is needed
# curr_datetime = datetime.datetime(2016, 1, 7, 10, 52, 23, tzinfo=pytz.UTC)
match = re.match('([1-9][0-9]*)([smhdwMY])', delta_time_string)
if match is None:
return None
num_units = int(match.group(1))
unit_char = match.group(2)
seconds_per_unit = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400, 'w': 604800}
if unit_char in seconds_per_unit:
delta_secs = (int(seconds_per_unit[unit_char]) * num_units) - slop
return curr_datetime - datetime.timedelta(seconds=delta_secs)
elif unit_char == 'M':
month = curr_datetime.month - 1 - num_units
year = int(curr_datetime.year + month / 12)
month = month % 12 + 1
day = min(curr_datetime.day, calendar.monthrange(year, month)[1])
return datetime.datetime(year, month, day, curr_datetime.hour, curr_datetime.minute, curr_datetime.second,
tzinfo=pytz.UTC) - datetime.timedelta(seconds=slop)
else: # unit_char == 'Y'
return datetime.datetime(curr_datetime.year + num_units, curr_datetime.month, curr_datetime.day,
curr_datetime.hour, curr_datetime.minute, curr_datetime.second, tzinfo=pytz.UTC) - \
datetime.timedelta(seconds=slop)
评论列表
文章目录