Skip to content

Commit 4c25a8b

Browse files
committed
Move datetime to new util function and add test.
1 parent 609aa27 commit 4c25a8b

File tree

3 files changed

+42
-2
lines changed

3 files changed

+42
-2
lines changed

heudiconv/bids.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
json_dumps_pretty,
2222
set_readonly,
2323
is_readonly,
24+
get_datetime,
2425
)
2526

2627
lgr = logging.getLogger(__name__)
@@ -407,8 +408,7 @@ def get_formatted_scans_key_row(dcm_fn):
407408
try:
408409
date = dcm_data.ContentDate
409410
time = dcm_data.ContentTime
410-
td = time + ':' + date
411-
acq_time = datetime.strptime(td, '%H%M%S.%f:%Y%m%d').isoformat()
411+
acq_time = get_datetime(date, time)
412412
except (AttributeError, ValueError) as exc:
413413
lgr.warning("Failed to get date/time for the content: %s", str(exc))
414414
acq_time = ''

heudiconv/tests/test_utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
load_json,
1111
create_tree,
1212
save_json,
13+
get_datetime,
1314
JSONDecodeError)
1415

1516
import pytest
@@ -85,3 +86,17 @@ def test_load_json(tmpdir, caplog):
8586
save_json(valid_json_file, vcontent)
8687

8788
assert load_json(valid_json_file) == vcontent
89+
90+
91+
def test_get_datetime():
92+
"""
93+
Test utils.get_datetime()
94+
"""
95+
date = '20200512'
96+
time = '162130'
97+
datetime_str = get_datetime(date, time)
98+
assert datetime_str == '2020-05-12T16:21:30.000000'
99+
date = '20200512'
100+
time = '162130.5'
101+
datetime_str = get_datetime(date, time)
102+
assert datetime_str == '2020-05-12T16:21:30.500000'

heudiconv/utils.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from collections import namedtuple
1414
from glob import glob
1515
from subprocess import check_output
16+
from datetime import datetime
1617

1718
from nipype.utils.filemanip import which
1819

@@ -505,3 +506,27 @@ def get_typed_attr(obj, attr, _type, default=None):
505506
except (TypeError, ValueError):
506507
return default
507508
return val
509+
510+
511+
def get_datetime(date, time):
512+
"""
513+
Convert date and time from dicom to isoformat.
514+
515+
Parameters
516+
----------
517+
date : str
518+
Date in YYYYMMDD format.
519+
time : str
520+
Time in either HHMMSS.ffffff format or HHMMSS format.
521+
522+
Returns
523+
-------
524+
datetime_str : str
525+
Combined date and time in ISO format, with milliseconds.
526+
"""
527+
if '.' not in time:
528+
# add milliseconds if not available
529+
time += '.000'
530+
td = time + ':' + date
531+
datetime_str = datetime.strptime(td, '%H%M%S.%f:%Y%m%d').isoformat()
532+
return datetime_str

0 commit comments

Comments
 (0)