Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion csep/utils/time_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import calendar
import datetime
import re
import os
import warnings
from csep.utils.constants import SECONDS_PER_ASTRONOMICAL_YEAR, SECONDS_PER_DAY

Expand All @@ -17,8 +18,25 @@ def epoch_time_to_utc_datetime(epoch_time_milli):
"""
if epoch_time_milli is None:
return epoch_time_milli

epoch_time = epoch_time_milli / 1000
dt = datetime.datetime.fromtimestamp(epoch_time, datetime.timezone.utc)

if os.name == "nt" and epoch_time < 0:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When using Windows, check for negative timestamps, and handle it properly.


if isinstance(epoch_time, int):
sec = epoch_time
milli_sec = 0
else:
whole, frac = str(epoch_time).split(".")
sec = int(whole)
milli_sec = int(frac) * -1
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(
seconds=sec,
milliseconds=milli_sec
)
else:
dt = datetime.datetime.fromtimestamp(epoch_time, datetime.timezone.utc)

return dt

def datetime_to_utc_epoch(dt):
Expand Down
7 changes: 5 additions & 2 deletions tests/test_time_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,8 @@ def test_decimal_year_epoch(self):
test_year = decimal_year(epoch_time_to_utc_datetime(epoch))
self.assertAlmostEqual(year, test_year)



def test_negative_epoch(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Included test to check if negative timestamps are working properly.

year = 1969.12315213421321321
epoch = decimal_year_to_utc_epoch(year)
test_year = decimal_year(epoch_time_to_utc_datetime(epoch))
self.assertAlmostEqual(year, test_year)