Skip to content

Commit 5cb4aeb

Browse files
bite 128
1 parent 9b58a9e commit 5cb4aeb

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,4 @@
1515
/66/README.md
1616
/117/README.md
1717
/64/README.md
18+
/128/README.md

128/dt_convert.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from datetime import datetime
2+
3+
THIS_YEAR = 2018
4+
5+
6+
def years_ago(date):
7+
"""Receives a date string of 'DD MMM, YYYY', for example: 8 Aug, 2015
8+
Convert this date str to a datetime object (use strptime).
9+
Then extract the year from the obtained datetime object and subtract
10+
it from the THIS_YEAR constant above, returning the int difference.
11+
So in this example you would get: 2018 - 2015 = 3"""
12+
date = datetime.strptime(date, "%d %b, %Y")
13+
return THIS_YEAR-date.year
14+
15+
16+
def convert_eu_to_us_date(date):
17+
"""Receives a date string in European format of dd/mm/yyyy, e.g. 11/03/2002
18+
Convert it to an American date: mm/dd/yyyy (in this case 03/11/2002).
19+
To enforce the use of datetime's strptime / strftime (over slicing)
20+
the tests check if a ValueError is raised for invalid day/month/year
21+
ranges (no need to code this, datetime does this out of the box)"""
22+
datex = datetime.strptime(date, "%d/%m/%Y")
23+
return datex.strftime("%m/%d/%Y")
24+
25+
# print(convert_eu_to_us_date("02/02/2002"))

128/test_dt_convert.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import pytest
2+
3+
from dt_convert import years_ago, convert_eu_to_us_date
4+
5+
6+
def test_years_ago():
7+
assert years_ago('8 Aug, 2015') == 3
8+
assert years_ago('6 Sep, 2014') == 4
9+
assert years_ago('1 Oct, 2010') == 8
10+
assert years_ago('31 Dec, 1958') == 60
11+
12+
13+
def test_years_ago_wrong_input():
14+
with pytest.raises(ValueError):
15+
# Sept != valid %b value 'Sep'
16+
assert years_ago('6 Sept, 2014') == 4
17+
18+
19+
def test_convert_eu_to_us_date():
20+
assert convert_eu_to_us_date('11/03/2002') == '03/11/2002'
21+
assert convert_eu_to_us_date('18/04/2008') == '04/18/2008'
22+
assert convert_eu_to_us_date('12/12/2014') == '12/12/2014'
23+
assert convert_eu_to_us_date('1/3/2004') == '03/01/2004'
24+
25+
26+
def test_convert_eu_to_us_date_invalid_day():
27+
with pytest.raises(ValueError):
28+
convert_eu_to_us_date('41/03/2002')
29+
30+
31+
def test_convert_eu_to_us_date_invalid_month():
32+
with pytest.raises(ValueError):
33+
convert_eu_to_us_date('11/13/2002')
34+
35+
36+
def test_convert_eu_to_us_date_invalid_year():
37+
with pytest.raises(ValueError):
38+
convert_eu_to_us_date('11/13/year')

0 commit comments

Comments
 (0)