Skip to content

Commit

Permalink
Function to make datetime from separate date & time fields (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
pipliggins committed Jun 27, 2023
1 parent 81cd9a8 commit 6676e62
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
23 changes: 23 additions & 0 deletions adtl/transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,26 @@ def makeDateTimeFromSeconds(date, time_seconds, date_format, tzname):
hour = time_seconds // 3600
minute = (time_seconds % 3600) // 60
return t.replace(hour=hour, minute=minute).isoformat()


def makeDateTime(date, time_24hr, date_format, timezone):
"""Combine date and time fields into one"""
if date == "":
return None

try:
dt = datetime.strptime(date, date_format).replace(
tzinfo=zoneinfo.ZoneInfo(timezone)
)
except ValueError:
logging.error(
f"Could not convert date {date!r} from date format {date_format!r}"
)
return None

if time_24hr == "":
return dt.date().isoformat() # return date only

tm = datetime.strptime(time_24hr, "%H:%M").time()

return datetime.combine(dt, tm, tzinfo=zoneinfo.ZoneInfo(timezone)).isoformat()
16 changes: 16 additions & 0 deletions tests/test_transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,19 @@ def test_makeDateTimeFromSeconds(date, time_seconds, date_format, tzname, expect
)
def test_textIfNotNull(field, return_text, expected):
assert transform.textIfNotNull(field, return_text) == expected


@pytest.mark.parametrize(
"date,time,date_format,tzname,expected",
[
("", "00:00", "%d/%m/%Y", "UTC", None),
("04/05/2020", "10:00", "%d/%m/%Y", "UTC", "2020-05-04T10:00:00+00:00"),
("04/05/2020", "", "%d/%m/%Y", "UTC", "2020-05-04"),
("04/05/2020", "", "%m/%d/%Y", "UTC", "2020-04-05"),
("04/05/2020", "", "%Y-%m-%d", "UTC", None),
("05/06/2020", "16:00", "%d/%m/%Y", "UTC", "2020-06-05T16:00:00+00:00"),
("05/06/2020", "16:00", "%d/%m/%Y", "Asia/Tokyo", "2020-06-05T16:00:00+09:00"),
],
)
def test_makeDateTime(date, time, date_format, tzname, expected):
assert transform.makeDateTime(date, time, date_format, tzname) == expected

0 comments on commit 6676e62

Please sign in to comment.