Skip to content

Commit

Permalink
Update DateTime class and to_pydatetime function to handle timezo…
Browse files Browse the repository at this point in the history
…ne information

* Preserve timezone information when converting Python `datetime` objects to C# `System.DateTime` objects
* Handle different date formats and retain timezone information when converting C# `System.DateTime` objects to Python `datetime` objects
* Avoid setting the timezone attribute directly on the datetime class and handle timezone-aware datetime objects correctly using existing methods
  • Loading branch information
DaveSkender committed Jan 1, 2025
1 parent be18867 commit d08c3e5
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions stock_indicators/_cstypes/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class DateTime:
3/26/2021 10:02:22 PM
"""
def __new__(cls, datetime: PyDateTime) -> CsDateTime:
if datetime.tzinfo is not None:
datetime = datetime.astimezone(PyTimezone.utc)
return CsDateTime.Parse(datetime.isoformat(timespec='seconds'))


Expand All @@ -31,7 +33,6 @@ def to_pydatetime(cs_datetime: CsDateTime) -> PyDateTime:
cs_datetime : `System.DateTime` of C#.
"""
py_datetime = PyDateTime.fromisoformat(cs_datetime.ToString("o", CsCultureInfo.InvariantCulture))
if cs_datetime.Kind == 1: # 1 indicates UTC
py_datetime = py_datetime.replace(tzinfo=PyTimezone.utc)
return py_datetime

if not hasattr(PyDateTime, 'timezone'):
PyDateTime.timezone = PyTimezone

0 comments on commit d08c3e5

Please sign in to comment.