Python datetime 模块,timezone() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用datetime.timezone()

项目:gitnet    作者:networks-lab    | 项目源码 | 文件源码
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
项目:gitnet    作者:networks-lab    | 项目源码 | 文件源码
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
项目:qqbot.py    作者:yukixz    | 项目源码 | 文件源码
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)
项目:qqbot.py    作者:yukixz    | 项目源码 | 文件源码
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)
项目:threatdetectionservice    作者:flyballlabs    | 项目源码 | 文件源码
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
项目:two1-python    作者:21dotco    | 项目源码 | 文件源码
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
项目:smartchangelog    作者:ngouzy    | 项目源码 | 文件源码
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
项目:smartchangelog    作者:ngouzy    | 项目源码 | 文件源码
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
项目:veripress    作者:veripress    | 项目源码 | 文件源码
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
项目:dogbot    作者:moondropx    | 项目源码 | 文件源码
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)
项目:rets    作者:opendoor-labs    | 项目源码 | 文件源码
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)
项目:correios    作者:olist    | 项目源码 | 文件源码
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)))
项目:correios    作者:olist    | 项目源码 | 文件源码
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
项目:pipenv    作者:pypa    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:meta    作者:flowdas    | 项目源码 | 文件源码
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()
项目:authenticator    作者:JeNeSuisPasDave    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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)
项目:niconico-tools    作者:mo-san    | 项目源码 | 文件源码
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()
项目:niconico-tools    作者:mo-san    | 项目源码 | 文件源码
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()
项目:blog-a    作者:richardchien    | 项目源码 | 文件源码
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))
项目:blog-a    作者:richardchien    | 项目源码 | 文件源码
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
项目:queue-messaging    作者:socialwifi    | 项目源码 | 文件源码
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',
    }
项目:queue-messaging    作者:socialwifi    | 项目源码 | 文件源码
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',
    }
项目:queue-messaging    作者:socialwifi    | 项目源码 | 文件源码
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
项目:queue-messaging    作者:socialwifi    | 项目源码 | 文件源码
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'
项目:queue-messaging    作者:socialwifi    | 项目源码 | 文件源码
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'
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
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
项目:learn-python    作者:xushubo    | 项目源码 | 文件源码
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
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
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
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
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)
项目:suq    作者:MaxwellBo    | 项目源码 | 文件源码
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)
项目:threatdetectionservice    作者:flyballlabs    | 项目源码 | 文件源码
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}
项目:influxalchemy    作者:amancevice    | 项目源码 | 文件源码
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');"
项目:fudge    作者:bovarysme    | 项目源码 | 文件源码
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)
项目:minqlx-plugins    作者:dsverdlo    | 项目源码 | 文件源码
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))))
项目:facebook-ads-performance-downloader    作者:mara    | 项目源码 | 文件源码
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)
项目:saturn    作者:David-OConnor    | 项目源码 | 文件源码
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
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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"']
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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')
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:rets    作者:opendoor-labs    | 项目源码 | 文件源码
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)
项目:py-daily    作者:qorzj    | 项目源码 | 文件源码
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
项目:py-daily    作者:qorzj    | 项目源码 | 文件源码
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
项目:PaStA    作者:lfd    | 项目源码 | 文件源码
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)
项目:pipenv    作者:pypa    | 项目源码 | 文件源码
def FixedOffset(offset_hours, offset_minutes, name):
        return datetime.timezone(
            datetime.timedelta(
                hours=offset_hours, minutes=offset_minutes),
            name)
项目:pipenv    作者:pypa    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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"']