Skip to content

Instantly share code, notes, and snippets.

@joserc87
Created August 25, 2017 23:12
Show Gist options
  • Save joserc87/e05b906f960be05554cd076e140ddccc to your computer and use it in GitHub Desktop.
Save joserc87/e05b906f960be05554cd076e140ddccc to your computer and use it in GitHub Desktop.
Add date
# Code example to manipulate dates (add days to dates) by parsing the string.
# This is only useful when you cannot import datetime.
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) \
or (year % 400 is 0):
return True
else:
return False
def add_days_to_date(date_string, days_to_add):
# J F M A M J J A S O N D
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day, month, year = map(int, date_string.split('/'))
# February will have 29 days in leap years.
days_per_month[1] = 29 if is_leap_year(year) else 28
day += days_to_add
while day > days_per_month[month - 1]:
day -= days_per_month[month - 1]
month += 1
if month > 12:
month -= 12
year += 1
days_per_month[1] = 29 if is_leap_year(year) else 28
# In case we are going backwards
while day <= 0:
month -= 1
if month <= 0:
month += 12
year -= 1
days_per_month[1] = 29 if is_leap_year(year) else 28
day += days_per_month[month - 1]
return '{:02}/{:02}/{}'.format(day, month, year)
# To use it:
metadata_value = add_days_to_date('01/01/1970', 10000)
print(metadata_value)
metadata_value = add_days_to_date('01/01/1970', -10000)
print(metadata_value)
# Just to test that it works
tests = [('28/02/2017', 1, '01/03/2017'),
('28/02/2020', 1, '29/02/2020'),
('28/12/2017', 4, '01/01/2018'),
('01/01/2017', 31 + 28, '01/03/2017'),
('32/01/2017', 1, '02/02/2017'),
('01/01/2017', -1, '31/12/2016')
]
for start_date, days_to_add, expected_result in tests:
result = add_days_to_date(start_date, days_to_add)
assert result == expected_result, \
"Expected '{}' but got '{}'".format(expected_result, result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment