Created
October 28, 2015 14:50
-
-
Save mdsrosa/2aa433e5e09fcdab2e96 to your computer and use it in GitHub Desktop.
Add minutes to a date and subtract minutes from a date without using any Python library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
def sum_minutes_to_date(str_date, minutes): | |
date, hour = str_date.split(' ') | |
day, month, year = date.split('/') | |
day = int(day) | |
month_start_with_0 = False | |
if month.startswith('0'): month_start_with_0 = True | |
month = int(month) | |
year = int(year) | |
h, m = map(int, hour.split(':')) | |
minute = m + minutes | |
if minute >= 60: | |
if len(str(m)) == 1: m = '0{0}'.format(m) | |
h += 1 | |
if h >= 24: | |
day += 1 | |
h = '00' | |
else: | |
m = minute | |
if month_start_with_0: | |
month = '0{0}'.format(month) | |
return "%s/%s/%s %s:%s" % (day, month, year, h, m) | |
def subtract_minutes_from_date(str_date, minutes): | |
date, hour = str_date.split(' ') | |
day, month, year = date.split('/') | |
day = int(day) | |
month_start_with_0 = False | |
if month.startswith('0'): month_start_with_0 = True | |
month = int(month) | |
year = int(year) | |
h, m = map(int, hour.split(':')) | |
if minutes >= 60: | |
h -= minutes/60 | |
if len(str(m)) == 1: m = '0{0}'.format(m) | |
if h < 1: | |
day -= 1 | |
h = '00' | |
else: | |
m -= minutes | |
if month_start_with_0: | |
month = '0{0}'.format(month) | |
return "%s/%s/%s %s:%s" % (day, month, year, h, m) | |
def add_or_subtract_minutes_date(str_date, operation, minutes): | |
if operation in ('+', '-'): | |
if operation == '+': | |
return sum_minutes_to_date(str_date, minutes) | |
elif operation == '-': | |
return subtract_minutes_from_date(str_date, minutes) | |
else: | |
return'Invalid operation: {0}'.format(operation) | |
print add_or_subtract_minutes_date(sys.argv[1], sys.argv[2], int(sys.argv[3])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment