Python datetime.timezone() Examples

The following are code examples for showing how to use datetime.timezone(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: gitnet   Author: networks-lab   File: helpers.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def make_utc_date(dict):
    """
    Takes an attribute dictionary. If "date" present, returns "YYYY-MM-DD" in Coordinated Universal Time.
    Otherwise, returns None. "date" must be a git-formatted string, e.g. 'Mon Apr 18 00:59:02 2016 -0400'.

    **Parameters**:

    > *dict* : `dict`

    >> An attribute dictionary.

    **Return** `string` or `none`
    """
    if "date" in dict:
        git_dt = datetime_git(dict["date"]).astimezone(dt.timezone(dt.timedelta(0)))
        return git_dt.strftime("%Y-%m-%d")
    else:
        return None 
Example 2
Project: gitnet   Author: networks-lab   File: helpers.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def make_utc_datetime(dict):
    """
    Takes an attribute dictionary. If "date" present, returns "YYYY-MM-DD HH:MM:SS" in
    Coordinated Universal Time. Otherwise, returns None. "date" must be a git-formatted string,
    e.g. 'Mon Apr 18 00:59:02 2016 -0400'.

    **Parameters**:

    > *dict* : `dict`

    >> An attribute dictionary.

    **Return** `string` or `none`
    """
    if "date" in dict:
        git_dt = datetime_git(dict["date"]).astimezone(dt.timezone(dt.timedelta(0)))
        return git_dt.strftime("%Y-%m-%d %H:%M:%S")
    else:
        return None 
Example 3
Project: qqbot.py   Author: yukixz   File: twbot.py    (license) View Source Project 6 votes vote down vote up
def __str__(self):
        if self.user is None or self.date is None:
            error("Stringify `Tweet` without `user` or `date`.")
            raise ValueError()
        dt = self.date.astimezone(timezone(timedelta(hours=9)))
        ds = datetime.strftime(dt, "%Y-%m-%d %H:%M:%S JST")
        results = [self.user, ds]
        for t in [self.ja, self.zh]:
            if len(t) == 0:
                continue
            # Fix GBK encoding
            t = t.replace('?', '·')
            t = t.replace('?', '×')
            t = t.replace('#???', '')
            t = t.replace('#????????', '')
            results.extend(['', t.strip()])
        results.extend([str(m) for m in self.media])
        return '\n'.join(results) 
Example 4
Project: qqbot.py   Author: yukixz   File: twbot2.py    (license) View Source Project 6 votes vote down vote up
def __str__(self):
        if self.user is None or self.date is None:
            error("Stringify `Tweet` without `user` or `date`.")
            raise ValueError()
        dt = self.date.astimezone(timezone(timedelta(hours=9)))
        ds = datetime.strftime(dt, "%Y-%m-%d %H:%M:%S JST")
        results = [self.user, ds]
        for t in [self.ja, self.zh]:
            if len(t) == 0:
                continue
            # Fix GBK encoding
            t = t.replace('?', '·')
            t = t.replace('?', '×')
            t = t.replace('?', '')
            t = t.replace('#???', '')
            t = t.replace('#????????', '')
            results.extend(['', t.strip()])
        results.extend([str(m) for m in self.media])
        return '\n'.join(results) 
Example 5
Project: threatdetectionservice   Author: flyballlabs   File: time_funcs.py    (license) View Source Project 6 votes vote down vote up
def utcnow(format="ts"):
    ''' returns time-aware utc datetime object or timestamp of current time/date
        @Param: format  -  defaults to timestamp, provide "dt" for datetime obj '''

    dt = datetime.now(tz=pytz.utc)
    if format == "dt":
        return dt
    else: # timestamp includes millis down to 6th decimal place
        ts = str(dt.timestamp())
        return ts.replace('.', '')

# DEBUG
# print(utcnow())
# print(utcnow("dt"))

# TODO add methods for converting to client local timezone dynamically 
Example 6
Project: two1-python   Author: 21dotco   File: util.py    (license) View Source Project 6 votes vote down vote up
def format_date(unix_timestamp):
    """ Return a standardized date format for use in the two1 library.

    This function produces a localized datetime string that includes the UTC timezone offset. This offset is
    computed as the difference between the local version of the timestamp (python's datatime.fromtimestamp)
    and the utc representation of the input timestamp.

    Args:
        unix_timestamp (float): a floating point unix timestamp

    Returns:
        string: A string formatted with "%Y-%m-%d %H:%M:%S %Z"
    """

    local_datetime = datetime.fromtimestamp(unix_timestamp)
    utz_offset = local_datetime - datetime.utcfromtimestamp(unix_timestamp)
    local_date = local_datetime.replace(
        tzinfo=timezone(utz_offset)
    ).strftime("%Y-%m-%d %H:%M:%S %Z")

    return local_date 
Example 7
Project: smartchangelog   Author: ngouzy   File: test_datetools.py    (license) View Source Project 6 votes vote down vote up
def test_str2date():
    # GIVEN
    expected = datetime(
        year=2017,
        month=3,
        day=21,
        hour=16,
        minute=9,
        second=13,
        tzinfo=timezone(timedelta(hours=1))
    )
    string = '2017-03-21 16:09:13 +0100'
    # WHEN
    date = datetools.str2date(string)
    # THEN
    assert date == expected 
Example 8
Project: smartchangelog   Author: ngouzy   File: test_datetools.py    (license) View Source Project 6 votes vote down vote up
def test_date2str():
    # GIVEN
    expected = '2017-03-21 16:09:13 +0100'
    dt = datetime(
        year=2017,
        month=3,
        day=21,
        hour=16,
        minute=9,
        second=13,
        tzinfo=timezone(timedelta(hours=1))
    )
    # WHEN
    string = datetools.date2str(dt)
    # THEN
    assert string == expected 
Example 9
Project: veripress   Author: veripress   File: helpers.py    (license) View Source Project 6 votes vote down vote up
def timezone_from_str(tz_str):
    """
    Convert a timezone string to a timezone object.

    :param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
    :return: a timezone object (tzinfo)
    """
    m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
    if m:
        # in format 'UTC±[hh]:[mm]'
        delta_h = int(m.group(1))
        delta_m = int(m.group(2)) if delta_h >= 0 else -int(m.group(2))
        return timezone(timedelta(hours=delta_h, minutes=delta_m))

    # in format 'Asia/Shanghai'
    try:
        return pytz.timezone(tz_str)
    except pytz.exceptions.UnknownTimeZoneError:
        return None 
Example 10
Project: dogbot   Author: moondropx   File: models.py    (license) View Source Project 6 votes vote down vote up
def __str__(self):
        for url in self.media:
            filename = os.path.basename(url)
            dir = os.path.join(config['cq_root_dir'], config['cq_image_dir'], 'twitter')
            path = os.path.join(dir, filename)
            # ??twitter??????????
            if not os.path.exists(dir):
                os.mkdir(dir)
            # ??
            if not os.path.exists(path):
                resp = requests.get(url, timeout=60, proxies=config.get('proxies'))
                with open(path, 'wb') as f:
                    f.write(resp.content)

        dt = self.date.astimezone(timezone(timedelta(hours=9)))
        ds = datetime.strftime(dt, "%Y-%m-%d %H:%M:%S JST")
        results = [ds, ]
        text = self.text
        text = text.replace('?', '·').replace('?', '×').replace('#????????', '').replace('?', '')
        results.extend(['', text.strip()])
        results.extend([str(CQImage(os.path.join('twitter', os.path.basename(m)))) for m in self.media])
        return '\n'.join(results) 
Example 11
Project: rets   Author: opendoor-labs   File: decoder_test.py    (license) View Source Project 6 votes vote down vote up
def test_decode_time():
    assert _decode_time('03:04:05', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    # TODO: The standard specifies that the second fraction is limited to one
    # digit, however udatetime only permits 3 or 6 digits.
    assert _decode_time('03:04:05.600', True) == time(3, 4, 5, 600000, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05Z', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05+00:00', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05-00:00', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05+07:08', True) == time(3, 4, 5, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_time('03:04:05-07:08', True) == time(3, 4, 5, tzinfo=timezone(timedelta(hours=-7, minutes=-8)))
    assert _decode_time('03:04:05.600+07:08', True) == \
           time(3, 4, 5, 600000, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_time('03:04:05', False) == time(3, 4, 5)
    assert _decode_time('03:04:05.600', False) == time(3, 4, 5, 600000)
    assert _decode_time('03:04:05Z', False) == time(3, 4, 5)
    assert _decode_time('03:04:05+00:00', False) == time(3, 4, 5)
    assert _decode_time('03:04:05-00:00', False) == time(3, 4, 5)
    assert _decode_time('12:00:00+07:08', False) == time(4, 52)
    assert _decode_time('12:00:00-07:08', False) == time(19, 8) 
Example 12
Project: correios   Author: olist   File: test_user_models.py    (license) View Source Project 6 votes vote down vote up
def test_sanitize_contract_data(user):
    contract = Contract(
        user=user,
        number="9911222777  ",
        regional_direction="   10",
    )
    contract.customer_code = "279311"
    contract.status_code = "A"
    contract.start_date = "2014-05-09 00:00:00-03:00"
    contract.end_date = "2018-05-16 00:00:00-03:00"

    assert contract.number == 9911222777
    assert contract.regional_direction.number == 10
    assert contract.customer_code == 279311
    assert contract.status_code == "A"
    assert contract.start_date == datetime(2014, 5, 9, 0, 0, tzinfo=timezone(timedelta(hours=-3)))
    assert contract.end_date == datetime(2018, 5, 16, 0, 0, tzinfo=timezone(timedelta(hours=-3))) 
Example 13
Project: correios   Author: olist   File: test_user_models.py    (license) View Source Project 6 votes vote down vote up
def test_sanitize_posting_card_data(contract):
    posting_card = PostingCard(
        contract=contract,
        number="0056789123",
        administrative_code=8888888,
    )
    posting_card.start_date = "2014-05-09 00:00:00-03:00"
    posting_card.end_date = "2018-05-16 00:00:00-03:00"
    posting_card.status = "01"
    posting_card.status_code = "I"
    posting_card.unit = "08        "

    assert posting_card.number == "0056789123"
    assert posting_card.administrative_code == "08888888"
    assert posting_card.start_date == datetime(2014, 5, 9, 0, 0, tzinfo=timezone(timedelta(hours=-3)))
    assert posting_card.end_date == datetime(2018, 5, 16, 0, 0, tzinfo=timezone(timedelta(hours=-3)))
    assert posting_card.status == 1
    assert posting_card.status_code == "I"
    assert posting_card.unit == 8 
Example 14
Project: pipenv   Author: pypa   File: iso8601.py    (license) View Source Project 6 votes vote down vote up
def parse_timezone(matches, default_timezone=UTC):
    """Parses ISO 8601 time zone specs into tzinfo offsets

    """

    if matches["timezone"] == "Z":
        return UTC
    # This isn't strictly correct, but it's common to encounter dates without
    # timezones so I'll assume the default (which defaults to UTC).
    # Addresses issue 4.
    if matches["timezone"] is None:
        return default_timezone
    sign = matches["tz_sign"]
    hours = to_int(matches, "tz_hour")
    minutes = to_int(matches, "tz_minute", default_to_zero=True)
    description = "%s%02d:%02d" % (sign, hours, minutes)
    if sign == "-":
        hours = -hours
        minutes = -minutes
    return FixedOffset(hours, minutes, description) 
Example 15
Project: ouroboros   Author: pybee   File: utils.py    (license) View Source Project 6 votes vote down vote up
def format_datetime(dt, usegmt=False):
    """Turn a datetime into a date string as specified in RFC 2822.

    If usegmt is True, dt must be an aware datetime with an offset of zero.  In
    this case 'GMT' will be rendered instead of the normal +0000 required by
    RFC2822.  This is to support HTTP headers involving date stamps.
    """
    now = dt.timetuple()
    if usegmt:
        if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
            raise ValueError("usegmt option requires a UTC datetime")
        zone = 'GMT'
    elif dt.tzinfo is None:
        zone = '-0000'
    else:
        zone = dt.strftime("%z")
    return _format_timetuple_and_zone(now, zone) 
Example 16
Project: meta   Author: flowdas   File: stdtypes.py    (license) View Source Project 6 votes vote down vote up
def format(self, value, property, context):
        if isinstance(value, datetime.datetime):
            if value.tzinfo:
                # DST ? ???? ???.
                value = value.replace(tzinfo=timezone.utc) - value.utcoffset()
            return int(calendar.timegm(value.timetuple())) + (value.microsecond / 1000000.0)
        elif isinstance(value, datetime.time):
            seconds = value.hour * 3600 + value.minute * 60 + value.second
            if value.tzinfo:
                # DST ? ???? ???.
                seconds -= value.utcoffset().total_seconds()
            return seconds % 86400 + (value.microsecond / 1000000.0)
        elif isinstance(value, datetime.date):
            return calendar.timegm(value.timetuple())
        else:
            raise ValueError() 
Example 17
Project: authenticator   Author: JeNeSuisPasDave   File: test_ClientData.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, *args):
        """Constructor."""
        from datetime import datetime, timezone, timedelta

        # figure the local timezone
        #
        lt = datetime.now()
        ut = datetime.utcnow()
        lt2 = datetime.now()
        if ut.second == lt2.second:
            lt = lt2
        dt = ut - lt
        offset_minutes = 0
        if (0 == dt.days):
            offset_minutes = dt.seconds // 60
        else:
            dt = lt - ut
            offset_minutes = dt.seconds // 60
            offset_minutes *= -1
        dt = timedelta(minutes=offset_minutes)
        self.__tz = timezone(dt)
        self.__utz = timezone(timedelta(0))

        super().__init__(*args) 
Example 18
Project: kbe_server   Author: xiaohaoppy   File: utils.py    (license) View Source Project 6 votes vote down vote up
def format_datetime(dt, usegmt=False):
    """Turn a datetime into a date string as specified in RFC 2822.

    If usegmt is True, dt must be an aware datetime with an offset of zero.  In
    this case 'GMT' will be rendered instead of the normal +0000 required by
    RFC2822.  This is to support HTTP headers involving date stamps.
    """
    now = dt.timetuple()
    if usegmt:
        if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
            raise ValueError("usegmt option requires a UTC datetime")
        zone = 'GMT'
    elif dt.tzinfo is None:
        zone = '-0000'
    else:
        zone = dt.strftime("%z")
    return _format_timetuple_and_zone(now, zone) 
Example 19
Project: niconico-tools   Author: mo-san   File: nicoml.py    (license) View Source Project 6 votes vote down vote up
def _get_jst_from_utime(cls, timestamp):
        """
        UNIXTIME ???????????????'+09:00'??????

        1471084020 -> '2016-08-13 19:27:00'

        :param int timestamp: UNIXTIME???
        :rtype: str
        """
        return str(datetime.fromtimestamp(timestamp, timezone(timedelta(hours=+9))))[:-6]

    # @classmethod
    # def _get_utime(cls):
    #     """
    #     ??? UNIXTIME ????
    #
    #     '2016-08-13 19:27:00' -> 1471084020
    #
    #     :rtype: int
    #     """
    #     return datetime.now().timestamp() 
Example 20
Project: niconico-tools   Author: mo-san   File: nicoml_async.py    (license) View Source Project 6 votes vote down vote up
def _get_jst_from_utime(cls, timestamp):
        """
        UNIXTIME ???????????????'+09:00'??????

        1471084020 -> '2016-08-13 19:27:00'

        :param int timestamp: UNIXTIME???
        :rtype: str
        """
        return str(datetime.fromtimestamp(timestamp, timezone(timedelta(hours=+9))))[:-6]

    # @classmethod
    # def _get_utime(cls):
    #     """
    #     ??? UNIXTIME ????
    #
    #     '2016-08-13 19:27:00' -> 1471084020
    #
    #     :rtype: int
    #     """
    #     return datetime.now().timestamp() 
Example 21
Project: blog-a   Author: richardchien   File: util.py    (MIT License) View Source Project 5 votes vote down vote up
def timezone_from_str(tz_str):
    """
    Convert a timezone string to a timezone object

    :param tz_str: string with format 'UTC±[hh]:[mm]'
    :return: a timezone object
    """
    m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
    delta_h = int(m.group(1))
    delta_m = int(m.group(2)) if delta_h >= 0 else -int(m.group(2))
    return timezone(timedelta(hours=delta_h, minutes=delta_m)) 
Example 22
Project: blog-a   Author: richardchien   File: util.py    (MIT License) View Source Project 5 votes vote down vote up
def fix_datetime(dt):
    """
    Fix a datetime (supposed to be)

    :param dt: datetime to fix
    :return: correct datetime object
    """
    if isinstance(dt, date):
        dt = datetime(dt.year, dt.month, dt.day)
    if dt is not None and dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone_from_str(C.timezone))
    return dt 
Example 23
Project: queue-messaging   Author: socialwifi   File: test_encoding.py    (license) View Source Project 5 votes vote down vote up
def test_create_attributes():
    data = FancyEvent(
        string_field='123456789',
        uuid_field=uuid.UUID('72d9a041-f401-42b6-8556-72b3c00e43d8'),
    )
    now = datetime.datetime(2016, 12, 10, 11, 15, 45, tzinfo=datetime.timezone.utc)
    attributes = encoding.create_attributes(data, now=now)
    assert attributes == {
        'type': 'FancyEvent',
        'timestamp': '2016-12-10T11:15:45.000000Z',
    } 
Example 24
Project: queue-messaging   Author: socialwifi   File: test_encoding.py    (license) View Source Project 5 votes vote down vote up
def test_create_attributes_uses_current_date_for_timestamp(get_now_with_utc_timezone):
    data = FancyEvent(
        string_field='123456789',
        uuid_field=uuid.UUID('72d9a041-f401-42b6-8556-72b3c00e43d8'),
    )
    get_now_with_utc_timezone.return_value = datetime.datetime(
        2016, 12, 10, 11, 15, 45, tzinfo=datetime.timezone.utc)
    attributes = encoding.create_attributes(data)
    assert attributes == {
        'type': 'FancyEvent',
        'timestamp': '2016-12-10T11:15:45.000000Z',
    } 
Example 25
Project: queue-messaging   Author: socialwifi   File: test_encoding.py    (license) View Source Project 5 votes vote down vote up
def test_integration(self):
        input = datetime.datetime(2016, 12, 10, 11, 15, 45, 123456,
                                  tzinfo=datetime.timezone.utc)
        encoded = encoding.datetime_to_rfc3339_string(input)
        decoded = encoding.rfc3339_string_to_datetime(encoded)
        assert decoded == input 
Example 26
Project: queue-messaging   Author: socialwifi   File: test_encoding.py    (license) View Source Project 5 votes vote down vote up
def test_encoding_datetime_in_utc(self):
        input = datetime.datetime(2016, 12, 10, 11, 15, 45, 123456,
                                  tzinfo=datetime.timezone.utc)
        encoded = encoding.datetime_to_rfc3339_string(input)
        assert encoded == '2016-12-10T11:15:45.123456Z' 
Example 27
Project: queue-messaging   Author: socialwifi   File: test_encoding.py    (license) View Source Project 5 votes vote down vote up
def test_encoding_datetime_not_in_utc(self):
        some_timezone = datetime.timezone(datetime.timedelta(hours=-7))
        input = datetime.datetime(2016, 12, 10, 11, 15, 45, 123456,
                                  tzinfo=some_timezone)
        encoded = encoding.datetime_to_rfc3339_string(input)
        assert encoded == '2016-12-10T18:15:45.123456Z' 
Example 28
Project: ibstract   Author: jesseliu0   File: marketdata.py    (license) View Source Project 5 votes vote down vote up
def TimeEnd(self, timeend):
        if timeend is None:
            self._timeend = datetime.now(tz=pytz.utc)
        elif not isinstance(timeend, datetime):
            raise TypeError("req.TimeEnd must be a datetime.datetime object.")
        else:
            # Always use timezone-aware datetime.
            if timeend.tzinfo is None:
                _logger.warning('Naive HistDataReq.TimeEnd. '
                                'Assumeing system local time zone.')
                tz_system = get_localzone()
                timeend = tz_system.localize(timeend)
            self._timeend = timeend 
Example 29
Project: learn-python   Author: xushubo   File: module-datetime1.py    (license) View Source Project 5 votes vote down vote up
def to_timestamp(dt_str, tz_str):
	temp_time = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
	if re.match(r'^UTC\+([0-9]|0[0-9]|1[0-2]):00$', tz_str):
		temp_timezone = timezone(timedelta(hours=int(re.match(r'^UTC\+([0-9]|0[0-9]|1[0-2]):00$', tz_str).group(1))))
	elif re.match(r'^UTC\-([0-9]|0[0-9]|1[0-2]):00$', tz_str):
		temp_timezone = timezone(timedelta(hours=-int(re.match(r'^UTC\-([0-9]|0[0-9]|1[0-2]):00$', tz_str).group(1))))
	dt = temp_time.replace(tzinfo=temp_timezone)
	dt_timestamp = dt.timestamp()
	return dt_timestamp 
Example 30
Project: scarlett_os   Author: bossjones   File: dt.py    (license) View Source Project 5 votes vote down vote up
def get_time_zone(time_zone_str: str) -> Optional[dt.tzinfo]:
    """Get time zone from string. Return None if unable to determine.

    Async friendly.
    """
    try:
        return pytz.timezone(time_zone_str)
    except pytz.exceptions.UnknownTimeZoneError:
        return None 
Example 31
Project: scarlett_os   Author: bossjones   File: dt.py    (license) View Source Project 5 votes vote down vote up
def parse_datetime(dt_str: str) -> dt.datetime:
    """Parse a string and return a datetime.datetime.

    This function supports time zone offsets. When the input contains one,
    the output uses a timezone with a fixed offset from UTC.
    Raises ValueError if the input is well formatted but not a valid datetime.
    Returns None if the input isn't well formatted.
    """
    match = DATETIME_RE.match(dt_str)
    if not match:
        return None
    kws = match.groupdict()  # type: Dict[str, Any]
    if kws['microsecond']:
        kws['microsecond'] = kws['microsecond'].ljust(6, '0')
    tzinfo_str = kws.pop('tzinfo')

    tzinfo = None  # type: Optional[dt.tzinfo]
    if tzinfo_str == 'Z':
        tzinfo = UTC
    elif tzinfo_str is not None:
        offset_mins = int(tzinfo_str[-2:]) if len(tzinfo_str) > 3 else 0
        offset_hours = int(tzinfo_str[1:3])
        offset = dt.timedelta(hours=offset_hours, minutes=offset_mins)
        if tzinfo_str[0] == '-':
            offset = -offset
        tzinfo = dt.timezone(offset)
    else:
        tzinfo = None
    kws = {k: int(v) for k, v in kws.items() if v is not None}
    kws['tzinfo'] = tzinfo
    return dt.datetime(**kws) 
Example 32
Project: suq   Author: MaxwellBo   File: models.py    (license) View Source Project 5 votes vote down vote up
def cull_past_breaks(events: List[Break]) -> List[Break]:
    """
    Removes breaks before the current time
    """
     # Here be dragons: This is hardcoded to Brisbane's timezone
    now = datetime.now(BRISBANE_TIME_ZONE)

    return sorted([i for i in events if now < i.end], key=lambda i: i.start) 
Example 33
Project: threatdetectionservice   Author: flyballlabs   File: endpoint.py    (license) View Source Project 5 votes vote down vote up
def get(self, _mac_address_=None):
        URL = request.url
        
        # time sync
        if URL.find("api/picontroller/time") > 0 and _mac_address_ == None:
            try:
                dtz = timezone(-timedelta(hours=4))
                dtUTC = datetime.now(dtz)
                dtfUTC = datetime.strftime(dtUTC, '%Y-%m-%d %H:%M:%S')
                
                return jsonify(
                    status = 200,
                    datetime = dtfUTC
                )
            except Exception as e:
                return {'status' : 400}

        # get agent settings
        elif URL.find("api/picontroller") > 0 and _mac_address_ != None:
            try:
                x = agent_data.query.filter_by(mac_address=_mac_address_).first()
                _mode = x.mode
                _cmd = x.cmd
                _time_setting = x.time_setting

                if x != None:
                    return jsonify(
                        status = 200,
                        mode = _mode,
                        cmd = _cmd,
                        time_setting = _time_setting
                    )
                else:
                    return {'status' : 400}
            except Exception as e:
                return {'status' : 400}
        else:
            return {'status' : 404} 
Example 34
Project: influxalchemy   Author: amancevice   File: query_test.py    (license) View Source Project 5 votes vote down vote up
def test_filter_time_aware(mock_qry):
    mock_qry.side_effect = influxdb.exceptions.InfluxDBClientError(None)
    db = influxdb.InfluxDBClient(database="example")
    client = InfluxAlchemy(db)
    meas = Measurement.new("fizz")
    if sys.version_info.major >= 3:
        tz_vietnam = timezone(timedelta(hours=7, minutes=7))
    else:
        tz_vietnam = timezone('Asia/Ho_Chi_Minh')
    d_low = datetime(2016, 9, 1, tzinfo=tz_vietnam)
    d_high = datetime(2016, 10, 2, 8)
    query = client.query(meas).filter(meas.time.between(d_low, d_high))
    assert repr(query) == "SELECT * FROM fizz WHERE (time >= '2016-09-01T00:00:00+07:07' AND time <= '2016-10-02T08:00:00+00:00');" 
Example 35
Project: fudge   Author: bovarysme   File: commit.py    (license) View Source Project 5 votes vote down vote up
def datetime(self):
        timestamp = float(self.timestamp)

        hours, minutes = int(self.offset[0:3]), int(self.offset[3:5])
        timedelta = datetime.timedelta(hours=hours, minutes=minutes)
        timezone = datetime.timezone(timedelta)

        dt = datetime.datetime.fromtimestamp(timestamp, timezone)
        return '{} {}'.format(dt.strftime('%c'), self.offset) 
Example 36
Project: minqlx-plugins   Author: dsverdlo   File: myessentials.py    (license) View Source Project 5 votes vote down vote up
def cmd_time(self, player, msg, channel):
        """Responds with the current time."""
        tz_offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
        tz_offset = tz_offset // 60 // 60 * -1
        tz = datetime.timezone(offset=datetime.timedelta(hours=tz_offset))
        now = datetime.datetime.now(tz)

        if len(msg) > 1:

            try:
                tz_offset = int(msg[1])
                tz = datetime.timezone(offset=datetime.timedelta(hours=tz_offset))
                now = datetime.datetime.now(tz)
            except ValueError:
                self.after_command(lambda:
                channel.reply("Unintelligible time zone offset."))
                return

        if tz_offset > 0:
            self.after_command(lambda:
            channel.reply("The current time is: ^6{} UTC+{}"
                .format(now.strftime(TIME_FORMAT), tz_offset)))
        elif tz_offset < 0:
            self.after_command(lambda:
                channel.reply("The current time is: ^6{} UTC{}"
                .format(now.strftime(TIME_FORMAT), tz_offset)))
        else:
            self.after_command(lambda:
            channel.reply("The current time is: ^6{} UTC"
                .format(now.strftime(TIME_FORMAT)))) 
Example 37
Project: facebook-ads-performance-downloader   Author: mara   File: downloader.py    (license) View Source Project 5 votes vote down vote up
def download_ad_performance(ad_accounts: [adaccount.AdAccount]):
    """Download the Facebook ad performance and upserts them
    into a sqlite database per account and day

    Args:
        ad_accounts: A list of all ad accounts to download.

    """
    for account_index, ad_account in enumerate(ad_accounts):
        logging.info('Downloading data for account %s (account %d of %d)', ad_account['account_id'], account_index, len(ad_accounts))
        # calculate yesterday based on the timezone of the ad account
        ad_account_timezone = datetime.timezone(datetime.timedelta(
            hours=float(ad_account['timezone_offset_hours_utc'])))
        last_date = datetime.datetime.now(ad_account_timezone).date() - datetime.timedelta(days=1)
        first_date = _first_download_date_of_ad_account(ad_account)

        # check for ad performance db on the first day the account
        current_date = last_date
        while current_date >= first_date:
            db_name = ensure_data_directory(
                Path("{date:%Y/%m/%d}/facebook/ad-performance-act_{account_id}.sqlite3"
                     .format(date=current_date,
                             account_id=ad_account['account_id'])))

            if (not db_name.is_file()
                or (last_date - current_date).days <= int(config.redownload_window())):
                ad_insights = get_account_ad_performance_for_single_day(ad_account,
                                                                        current_date)
                with sqlite3.connect(str(db_name)) as con:
                    _upsert_ad_performance(ad_insights, con)
            current_date -= datetime.timedelta(days=1) 
Example 38
Project: saturn   Author: David-OConnor   File: from_arrow.py    (license) View Source Project 5 votes vote down vote up
def parse_tzinfo(string):
    """Find the tzinfo object associated with a string."""
    if string.upper() == 'UTC':
        return pytz.utc

    # ISO match searches for a string in format '+04:00'
    iso_match = RES['tzinfo'].match(string)
    if iso_match:
        sign, hours, minutes = iso_match.groups()
        if minutes is None:
            minutes = 0

        sign = -1 if sign == '-' else 1
        hours, minutes = int(hours), int(minutes)

        tzinfo = datetime.timezone(sign * datetime.timedelta(hours=hours,
                                                             minutes=minutes))

    # If not, it might be something like 'US/Eastern' that tzinfo can parse..
    else:
        tzinfo = pytz.timezone(string)

    if tzinfo is None:
        raise ParserError('Could not parse timezone expression "{0}"', string)

    return tzinfo 
Example 39
Project: web_ctp   Author: molebot   File: test_imaplib.py    (license) View Source Project 5 votes vote down vote up
def timevalues(self):
        return [2000000000, 2000000000.0, time.localtime(2000000000),
                (2033, 5, 18, 5, 33, 20, -1, -1, -1),
                (2033, 5, 18, 5, 33, 20, -1, -1, 1),
                datetime.fromtimestamp(2000000000,
                                       timezone(timedelta(0, 2*60*60))),
                '"18-May-2033 05:33:20 +0200"'] 
Example 40
Project: web_ctp   Author: molebot   File: test_imaplib.py    (license) View Source Project 5 votes vote down vote up
def test_that_Time2Internaldate_returns_a_result(self):
        # Without tzset, we can check only that it successfully
        # produces a result, not the correctness of the result itself,
        # since the result depends on the timezone the machine is in.
        for t in self.timevalues():
            imaplib.Time2Internaldate(t) 
Example 41
Project: web_ctp   Author: molebot   File: test_utils.py    (license) View Source Project 5 votes vote down vote up
def test_usegmt(self):
        utc_dt = datetime.datetime(*self.dateargs,
                                   tzinfo=datetime.timezone.utc)
        self.assertEqual(utils.format_datetime(utc_dt, usegmt=True),
                         self.datestring + ' GMT') 
Example 42
Project: web_ctp   Author: molebot   File: test_utils.py    (license) View Source Project 5 votes vote down vote up
def test_localtime_epoch_utc_daylight_true(self):
        test.support.patch(self, time, 'daylight', True)
        t0 = datetime.datetime(1990, 1, 1, tzinfo = datetime.timezone.utc)
        t1 = utils.localtime(t0)
        t2 = t0 - datetime.timedelta(hours=5)
        t2 = t2.replace(tzinfo = datetime.timezone(datetime.timedelta(hours=-5)))
        self.assertEqual(t1, t2) 
Example 43
Project: web_ctp   Author: molebot   File: test_utils.py    (license) View Source Project 5 votes vote down vote up
def test_localtime_epoch_utc_daylight_false(self):
        test.support.patch(self, time, 'daylight', False)
        t0 = datetime.datetime(1990, 1, 1, tzinfo = datetime.timezone.utc)
        t1 = utils.localtime(t0)
        t2 = t0 - datetime.timedelta(hours=5)
        t2 = t2.replace(tzinfo = datetime.timezone(datetime.timedelta(hours=-5)))
        self.assertEqual(t1, t2) 
Example 44
Project: rets   Author: opendoor-labs   File: decoder_test.py    (license) View Source Project 5 votes vote down vote up
def test_decode_datetime():
    assert _decode_datetime('2017-01-02T03:04:05', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(0)))
    # TODO: The standard specifies that the second fraction is limited to one
    # digit, however udatetime only permits 3 or 6 digits.
    assert _decode_datetime('2017-01-02T03:04:05.600', True) == \
           datetime(2017, 1, 2, 3, 4, 5, 600000, tzinfo=timezone(timedelta(0)))
    assert _decode_datetime('2017-01-02T03:04:05Z', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_datetime('2017-01-02T03:04:05+00:00', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_datetime('2017-01-02T03:04:05-00:00', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_datetime('2017-01-02T03:04:05+07:08', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_datetime('2017-01-02T03:04:05.600+07:08', True) == \
           datetime(2017, 1, 2, 3, 4, 5, 600000, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_datetime('2017-01-02T03:04:05-07:08', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(hours=-7, minutes=-8)))
    assert _decode_datetime('2017-01-02T03:04:05', False) == \
           datetime(2017, 1, 2, 3, 4, 5)
    assert _decode_datetime('2017-01-02T03:04:05.600', False) == \
           datetime(2017, 1, 2, 3, 4, 5, 600000)
    assert _decode_datetime('2017-01-02T03:04:05Z', False) == datetime(2017, 1, 2, 3, 4, 5)
    assert _decode_datetime('2017-01-02T03:04:05+00:00', False) == datetime(2017, 1, 2, 3, 4, 5)
    assert _decode_datetime('2017-01-02T03:04:05-00:00', False) == datetime(2017, 1, 2, 3, 4, 5)
    assert _decode_datetime('2017-01-02T12:00:00+07:08', False) == datetime(2017, 1, 2, 4, 52)
    assert _decode_datetime('2017-01-02T12:00:00-07:08', False) == datetime(2017, 1, 2, 19, 8) 
Example 45
Project: py-daily   Author: qorzj   File: solution.py    (license) View Source Project 5 votes vote down vote up
def date_distance(date_str):
    tz = timezone(timedelta(hours=8))
    now_date = datetime.now(tz).date()
    fmt = '%Y-%m-%d'
    post_date = datetime.strptime(date_str, fmt)
    post_date = post_date.replace(tzinfo=tz).date()
    return (post_date - now_date).days 
Example 46
Project: py-daily   Author: qorzj   File: solution.py    (license) View Source Project 5 votes vote down vote up
def date_distance(date_str)->int:
    tz=timezone(timedelta(hours=8))
    targetDate = datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=tz)
    now = datetime.now(tz)
    return (now-targetDate).days 
Example 47
Project: PaStA   Author: lfd   File: Repository.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, repo, commit_hash):
        commit = repo[commit_hash]

        auth_tz = timezone(timedelta(minutes=commit.author.offset))
        commit_tz = timezone(timedelta(minutes=commit.commit_time_offset))

        author_date = datetime.fromtimestamp(commit.author.time, auth_tz)
        commit_date = datetime.fromtimestamp(commit.commit_time, commit_tz)

        # default: diff is empty. This filters merge commits and commits with no
        # parents
        diff = ''
        if len(commit.parents) == 1:
            diff = repo.diff(commit.parents[0], commit).patch
            # there may be empty commits
            if not diff:
                diff = ''

        self.commit_hash = commit.hex

        self.committer = commit.committer.name
        self.committer_email = commit.committer.email
        self.commit_date = commit_date

        # split message and diff at newlines
        message = commit.message.split('\n')
        diff = diff.split('\n')

        super(Commit, self).__init__(message, diff, commit.author.name,
                                     commit.author.email, author_date) 
Example 48
Project: pipenv   Author: pypa   File: iso8601.py    (license) View Source Project 5 votes vote down vote up
def FixedOffset(offset_hours, offset_minutes, name):
        return datetime.timezone(
            datetime.timedelta(
                hours=offset_hours, minutes=offset_minutes),
            name) 
Example 49
Project: pipenv   Author: pypa   File: iso8601.py    (license) View Source Project 5 votes vote down vote up
def parse_date(datestring, default_timezone=UTC):
    """Parses ISO 8601 dates into datetime objects

    The timezone is parsed from the date string. However it is quite common to
    have dates without a timezone (not strictly correct). In this case the
    default timezone specified in default_timezone is used. This is UTC by
    default.

    :param datestring: The date to parse as a string
    :param default_timezone: A datetime tzinfo instance to use when no timezone
                             is specified in the datestring. If this is set to
                             None then a naive datetime object is returned.
    :returns: A datetime.datetime instance
    :raises: ParseError when there is a problem parsing the date or
             constructing the datetime instance.

    """
    if not isinstance(datestring, _basestring):
        raise ParseError("Expecting a string %r" % datestring)
    m = ISO8601_REGEX.match(datestring)
    if not m:
        raise ParseError("Unable to parse date string %r" % datestring)
    groups = m.groupdict()

    tz = parse_timezone(groups, default_timezone=default_timezone)

    groups["second_fraction"] = int(Decimal("0.%s" % (groups["second_fraction"] or 0)) * Decimal("1000000.0"))

    try:
        return datetime.datetime(
            year=to_int(groups, "year"),
            month=to_int(groups, "month", default=to_int(groups, "monthdash", required=False, default=1)),
            day=to_int(groups, "day", default=to_int(groups, "daydash", required=False, default=1)),
            hour=to_int(groups, "hour", default_to_zero=True),
            minute=to_int(groups, "minute", default_to_zero=True),
            second=to_int(groups, "second", default_to_zero=True),
            microsecond=groups["second_fraction"],
            tzinfo=tz,
        )
    except Exception as e:
        raise ParseError(e) 
Example 50
Project: ouroboros   Author: pybee   File: test_imaplib.py    (license) View Source Project 5 votes vote down vote up
def timevalues(self):
        return [2000000000, 2000000000.0, time.localtime(2000000000),
                (2033, 5, 18, 5, 33, 20, -1, -1, -1),
                (2033, 5, 18, 5, 33, 20, -1, -1, 1),
                datetime.fromtimestamp(2000000000,
                                       timezone(timedelta(0, 2*60*60))),
                '"18-May-2033 05:33:20 +0200"']