<commit_before>"""
Created on 13 Aug 2016

@author: <NAME> (<EMAIL>)
"""

import re

from datetime import datetime
from datetime import timedelta
from datetime import timezone

import tzlocal

from scs_core.data.json import JSONable


# --------------------------------------------------------------------------------------------------------------------

class LocalizedDatetime(JSONable):
    """
    classdocs
    """

    @classmethod
    def now(cls):
        zone = tzlocal.get_localzone()
        localized = datetime.now(zone)

        return LocalizedDatetime(localized)


    @classmethod
    def construct_from_timestamp(cls, t):
        zone = tzlocal.get_localzone()
        localized = datetime.fromtimestamp(t, zone)

        return LocalizedDatetime(localized)


    @classmethod
    def construct_from_iso8601(cls, datetime_str):
        # Z timezone offset...
        localized = cls.__construct_from_iso8601_z(datetime_str)

        if localized:
            return localized

        # numeric timezone offset...
        return cls.__construct_from_iso8601_numeric(datetime_str)


    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def __construct_from_iso8601_z(cls, datetime_str):
        # match...
        match = re.match('(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z', datetime_str)

        if match is None:
            return None

        fields = match.groups()

        # fields...
        year = int(fields[0])
        month = int(fields[1])
        date = int(fields[2])

        hours = int(fields[3])
        mins = int(fields[4])
        secs = int(fields[5])
        micros = int(fields[6]) * 1000

        # construct...
        zone_offset = timedelta(hours=0, minutes=0)
        zone = timezone(zone_offset)

        localized = datetime(year, month, date, hours, mins, secs, micros, tzinfo=zone)

        return LocalizedDatetime(localized)


    @classmethod
    def __construct_from_iso8601_numeric(cls, datetime_str):
        # match...
        match = re.match('(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})([ +\-]?)(\d{2}):(\d{2})',
                         datetime_str)

        if match is None:
            return None

        fields = match.groups()

        # fields...
        year = int(fields[0])
        month = int(fields[1])
        date = int(fields[2])

        hours = int(fields[3])
        mins = int(fields[4])
        secs = int(fields[5])
        micros = int(fields[6]) * 1000

        zone_sign = -1 if fields[7] == '-' else 1
        zone_hours = int(fields[8])
        zone_mins = int(fields[9])

        # construct...
        zone_offset = zone_sign * timedelta(hours=zone_hours, minutes=zone_mins)
        zone = timezone(zone_offset)

        localized = datetime(year, month, date, hours, mins, secs, micros, tzinfo=zone)

        return LocalizedDatetime(localized)


    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, localized):
        """
        Constructor
        """
        self.__localized = localized            # datetime


    def __add__(self, other: datetime):
        return LocalizedDatetime(self.__localized + other)


    def __sub__(self, other):
        other_datetime = other.__localized if type(other) == LocalizedDatetime else other

        return self.__localized - other_datetime


    # ----------------------------------------------------------------------------------------------------------------

    def timedelta(self, days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0):
        td = timedelta(days=days, seconds=seconds, microseconds=microseconds, milliseconds=milliseconds,
                       minutes=minutes, hours=hours, weeks=weeks)

        return LocalizedDatetime(self.__localized + td)


    # ----------------------------------------------------------------------------------------------------------------

    def as_iso8601(self):
        """
        example: 2016-08-13T00:38:05.210+00:00
        """
        date = self.__localized.strftime("%Y-%m-%d")
        time = self.__localized.strftime("%H:%M:%S")

        micros = float(self.__localized.strftime("%f"))
        millis = "%03d" % (micros // 1000)

        zone = self.__localized.strftime("%z")
        zone_hours = zone[:3]
        zone_mins = zone[3:]

        return "%sT%s.%s%s:%s" % (date, time, millis, zone_hours, zone_mins)


    def as_json(self):
        return self.as_iso8601()


    def timestamp(self):
        return self.__localized.timestamp()


    # ----------------------------------------------------------------------------------------------------------------

    @property
    def localized(self):
        return self.__localized


    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "LocalizedDatetime:{localized:%s}" % self.localized<commit_msg>Added DS1338 RTC class.<commit_after>"""
Created on 13 Aug 2016

@author: <NAME> (<EMAIL>)

http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/
"""

import re

from datetime import datetime
from datetime import timedelta
from datetime import timezone

import tzlocal

from scs_core.data.json import JSONable


# --------------------------------------------------------------------------------------------------------------------

class LocalizedDatetime(JSONable):
    """
    classdocs
    """

    @classmethod
    def now(cls):
        zone = tzlocal.get_localzone()
        localized = datetime.now(zone)

        return LocalizedDatetime(localized)


    @classmethod
    def construct_from_timestamp(cls, t):
        zone = tzlocal.get_localzone()
        localized = datetime.fromtimestamp(t, zone)

        return LocalizedDatetime(localized)


    @classmethod
    def construct_from_iso8601(cls, datetime_str):
        # Z timezone offset...
        localized = cls.__construct_from_iso8601_z(datetime_str)

        if localized:
            return localized

        # numeric timezone offset...
        return cls.__construct_from_iso8601_numeric(datetime_str)


    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def __construct_from_iso8601_z(cls, datetime_str):
        # match...
        match = re.match('(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z', datetime_str)

        if match is None:
            return None

        fields = match.groups()

        # fields...
        year = int(fields[0])
        month = int(fields[1])
        date = int(fields[2])

        hours = int(fields[3])
        mins = int(fields[4])
        secs = int(fields[5])
        micros = int(fields[6]) * 1000

        # construct...
        zone_offset = timedelta(hours=0, minutes=0)
        zone = timezone(zone_offset)

        localized = datetime(year, month, date, hours, mins, secs, micros, tzinfo=zone)

        return LocalizedDatetime(localized)


    @classmethod
    def __construct_from_iso8601_numeric(cls, datetime_str):
        # match...
        match = re.match('(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})([ +\-]?)(\d{2}):(\d{2})',
                         datetime_str)

        if match is None:
            return None

        fields = match.groups()

        # fields...
        year = int(fields[0])
        month = int(fields[1])
        date = int(fields[2])

        hours = int(fields[3])
        mins = int(fields[4])
        secs = int(fields[5])
        micros = int(fields[6]) * 1000

        zone_sign = -1 if fields[7] == '-' else 1
        zone_hours = int(fields[8])
        zone_mins = int(fields[9])

        # construct...
        zone_offset = zone_sign * timedelta(hours=zone_hours, minutes=zone_mins)
        zone = timezone(zone_offset)

        localized = datetime(year, month, date, hours, mins, secs, micros, tzinfo=zone)

        return LocalizedDatetime(localized)


    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, localized):
        """
        Constructor
        """
        self.__datetime = localized            # datetime


    def __add__(self, other: datetime):
        return LocalizedDatetime(self.__datetime + other)


    def __sub__(self, other):
        other_datetime = other.__datetime if type(other) == LocalizedDatetime else other

        return self.__datetime - other_datetime


    # ----------------------------------------------------------------------------------------------------------------

    def localize(self, zone):
        localized = zone.localize(self.__datetime)

        return LocalizedDatetime(localized)


    def timedelta(self, days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0):
        td = timedelta(days=days, seconds=seconds, microseconds=microseconds, milliseconds=milliseconds,
                       minutes=minutes, hours=hours, weeks=weeks)

        return LocalizedDatetime(self.__datetime + td)


    # ----------------------------------------------------------------------------------------------------------------

    def as_iso8601(self):
        """
        example: 2016-08-13T00:38:05.210+00:00
        """
        date = self.__datetime.strftime("%Y-%m-%d")
        time = self.__datetime.strftime("%H:%M:%S")

        micros = float(self.__datetime.strftime("%f"))
        millis = "%03d" % (micros // 1000)

        zone = self.__datetime.strftime("%z")
        zone_hours = zone[:3]
        zone_mins = zone[3:]

        return "%sT%s.%s%s:%s" % (date, time, millis, zone_hours, zone_mins)


    def as_json(self):
        return self.as_iso8601()


    def timestamp(self):
        return self.__datetime.timestamp()


    # ----------------------------------------------------------------------------------------------------------------

    @property
    def datetime(self):
        return self.__datetime


    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "LocalizedDatetime:{datetime:%s}" % self.datetime
{'fraction_non_alphanumeric': 0.26405516712958527, 'fraction_numerical': 0.02298630399387032, 'mean_word_length': 1.4697256385998108, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5268400', 'n_tokens_mistral': 3043, 'n_tokens_neox': 2738, 'n_words': 558}