Skip to content

Convert Date object to datetime with timezone information #167

@BGWKlein

Description

@BGWKlein

A method for HydPy Date objects returning a datetime object with timezone information would be usefull, something like:

from datetime import timezone,timedelta
    
def to_datetime(self, utcoffset: int | None = None) -> datetime:
        """Return a |datetime| object representing the actual date and the eventually given UTC offset (in minutes).

        >>> from hydpy import Date
        >>> date = Date("01.11.1997 00:00:00")
        >>> date.to_datetime()
        datetime.datetime(1997, 11, 1, 0, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))

        Passing utcoffset converts the datetime object from the local offset defined by
        |Options.utcoffset| (which defaults to UTC+01:00) to `utcoffset` :

        >>> date.to_datetime(utcoffset=60)
        datetime.datetime(1997, 11, 1, 0, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))

        >>> date.to_datetime(utcoffset=0)
        datetime.datetime(1997, 10, 31, 23, 0, tzinfo=datetime.timezone.utc)

        """
        date = self.datetime.replace(tzinfo=timezone(timedelta(minutes=pub.options.utcoffset)))
        
        if utcoffset is not None:
           date = date.astimezone(timezone(timedelta(minutes=utcoffset)))
        return date

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions