Skip to content

Commit

Permalink
Merge pull request #4025 from toshihikoyanase/specify-timespec-not-to…
Browse files Browse the repository at this point in the history
…-skip-microseconds

Avoid parse errors of `datetime.isoformat` strings
  • Loading branch information
c-bata committed Sep 29, 2022
2 parents 31da4d0 + cee4443 commit e8abeec
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
14 changes: 9 additions & 5 deletions optuna/storages/_journal/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def get_all_studies(self) -> List[FrozenStudy]:
def create_new_trial(self, study_id: int, template_trial: Optional[FrozenTrial] = None) -> int:
log: Dict[str, Any] = {
"study_id": study_id,
"datetime_start": datetime.datetime.now().isoformat(),
"datetime_start": datetime.datetime.now().isoformat(timespec="microseconds"),
}

if template_trial:
Expand All @@ -188,11 +188,15 @@ def create_new_trial(self, study_id: int, template_trial: Optional[FrozenTrial]
log["value"] = template_trial.value
log["values"] = None
if template_trial.datetime_start:
log["datetime_start"] = template_trial.datetime_start.isoformat()
log["datetime_start"] = template_trial.datetime_start.isoformat(
timespec="microseconds"
)
else:
log["datetime_start"] = None
if template_trial.datetime_complete:
log["datetime_complete"] = template_trial.datetime_complete.isoformat()
log["datetime_complete"] = template_trial.datetime_complete.isoformat(
timespec="microseconds"
)

log["distributions"] = {
k: distribution_to_json(dist) for k, dist in template_trial.distributions.items()
Expand Down Expand Up @@ -249,9 +253,9 @@ def set_trial_state_values(
}

if state == TrialState.RUNNING:
log["datetime_start"] = datetime.datetime.now().isoformat()
log["datetime_start"] = datetime.datetime.now().isoformat(timespec="microseconds")
elif state.is_finished():
log["datetime_complete"] = datetime.datetime.now().isoformat()
log["datetime_complete"] = datetime.datetime.now().isoformat(timespec="microseconds")

with self._thread_lock:
self._write_log(JournalOperation.SET_TRIAL_STATE_VALUES, log)
Expand Down
10 changes: 7 additions & 3 deletions tests/storages_tests/test_storages.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,10 +360,14 @@ def _check_trials(


@pytest.mark.parametrize("storage_mode", STORAGE_MODES)
def test_create_new_trial_with_template_trial(storage_mode: str) -> None:
@pytest.mark.parametrize(
"start_time,complete_time",
[(datetime.now(), datetime.now()), (datetime(2022, 9, 1), datetime(2022, 9, 2))],
)
def test_create_new_trial_with_template_trial(
storage_mode: str, start_time: datetime, complete_time: datetime
) -> None:

start_time = datetime.now()
complete_time = datetime.now()
template_trial = FrozenTrial(
state=TrialState.COMPLETE,
value=10000,
Expand Down

0 comments on commit e8abeec

Please sign in to comment.