Python django.utils.timezone.get_fixed_timezone() Examples

The following are 30 code examples of django.utils.timezone.get_fixed_timezone(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .
Example #1
Source File: dateparse.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def parse_datetime(value):
    """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.

    Raise ValueError if the input is well formatted but not a valid datetime.
    Return None if the input isn't well formatted.
    """
    match = datetime_re.match(value)
    if match:
        kw = match.groupdict()
        kw['microsecond'] = kw['microsecond'] and kw['microsecond'].ljust(6, '0')
        tzinfo = kw.pop('tzinfo')
        if tzinfo == 'Z':
            tzinfo = utc
        elif tzinfo is not None:
            offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
            offset = 60 * int(tzinfo[1:3]) + offset_mins
            if tzinfo[0] == '-':
                offset = -offset
            tzinfo = get_fixed_timezone(offset)
        kw = {k: int(v) for k, v in kw.items() if v is not None}
        kw['tzinfo'] = tzinfo
        return datetime.datetime(**kw) 
Example #2
Source File: test_dateparse.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_parse_datetime(self):
        valid_inputs = (
            ('2012-04-23T09:15:00', datetime(2012, 4, 23, 9, 15)),
            ('2012-4-9 4:8:16', datetime(2012, 4, 9, 4, 8, 16)),
            ('2012-04-23T09:15:00Z', datetime(2012, 4, 23, 9, 15, 0, 0, get_fixed_timezone(0))),
            ('2012-4-9 4:8:16-0320', datetime(2012, 4, 9, 4, 8, 16, 0, get_fixed_timezone(-200))),
            ('2012-04-23T10:20:30.400+02:30', datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150))),
            ('2012-04-23T10:20:30.400+02', datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(120))),
            ('2012-04-23T10:20:30.400-02', datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120))),
        )
        for source, expected in valid_inputs:
            with self.subTest(source=source):
                self.assertEqual(parse_datetime(source), expected)

        # Invalid inputs
        self.assertIsNone(parse_datetime('20120423091500'))
        with self.assertRaises(ValueError):
            parse_datetime('2012-04-56T09:15:90') 
Example #3
Source File: test_writer.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_serialize_datetime(self):
        self.assertSerializedEqual(datetime.datetime.utcnow())
        self.assertSerializedEqual(datetime.datetime.utcnow)
        self.assertSerializedEqual(datetime.datetime.today())
        self.assertSerializedEqual(datetime.datetime.today)
        self.assertSerializedEqual(datetime.date.today())
        self.assertSerializedEqual(datetime.date.today)
        self.assertSerializedEqual(datetime.datetime.now().time())
        self.assertSerializedEqual(datetime.datetime(2014, 1, 1, 1, 1, tzinfo=get_default_timezone()))
        self.assertSerializedEqual(datetime.datetime(2013, 12, 31, 22, 1, tzinfo=get_fixed_timezone(180)))
        self.assertSerializedResultEqual(
            datetime.datetime(2014, 1, 1, 1, 1),
            ("datetime.datetime(2014, 1, 1, 1, 1)", {'import datetime'})
        )
        self.assertSerializedResultEqual(
            datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc),
            (
                "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc)",
                {'import datetime', 'from django.utils.timezone import utc'},
            )
        ) 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_timezones(self):
        # Saving and updating with timezone-aware datetime Python objects.
        # Regression test for #10443.
        # The idea is that all these creations and saving should work without
        # crashing. It's not rocket science.
        dt1 = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=get_fixed_timezone(600))
        dt2 = datetime.datetime(2008, 8, 31, 17, 20, tzinfo=get_fixed_timezone(600))
        obj = Article.objects.create(
            headline="A headline", pub_date=dt1, article_text="foo"
        )
        obj.pub_date = dt2
        obj.save()
        self.assertEqual(
            Article.objects.filter(headline="A headline").update(pub_date=dt1),
            1
        ) 
Example #5
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_timezones(self):
        # Saving and updating with timezone-aware datetime Python objects.
        # Regression test for #10443.
        # The idea is that all these creations and saving should work without
        # crashing. It's not rocket science.
        dt1 = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=get_fixed_timezone(600))
        dt2 = datetime.datetime(2008, 8, 31, 17, 20, tzinfo=get_fixed_timezone(600))
        obj = Article.objects.create(
            headline="A headline", pub_date=dt1, article_text="foo"
        )
        obj.pub_date = dt2
        obj.save()
        self.assertEqual(
            Article.objects.filter(headline="A headline").update(pub_date=dt1),
            1
        ) 
Example #6
Source File: test_feedgenerator.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rfc2822_date_with_timezone(self):
        """
        rfc2822_date() correctly formats datetime objects with tzinfo.
        """
        self.assertEqual(
            feedgenerator.rfc2822_date(datetime.datetime(2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(60))),
            "Fri, 14 Nov 2008 13:37:00 +0100"
        ) 
Example #7
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_different_timezones(self):
        """ When using two different timezones. """
        now = datetime.datetime.now()
        now_tz = timezone.make_aware(now, timezone.get_default_timezone())
        now_tz_i = timezone.localtime(now_tz, timezone.get_fixed_timezone(195))

        self.assertEqual(timesince(now), '0\xa0minutes')
        self.assertEqual(timesince(now_tz), '0\xa0minutes')
        self.assertEqual(timesince(now_tz_i), '0\xa0minutes')
        self.assertEqual(timesince(now_tz, now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz, now_tz_i), '0\xa0minutes') 
Example #8
Source File: test_feedgenerator.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rfc3339_date_with_timezone(self):
        """
        rfc3339_date() correctly formats datetime objects with tzinfo.
        """
        self.assertEqual(
            feedgenerator.rfc3339_date(datetime.datetime(2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(120))),
            "2008-11-14T13:37:00+02:00"
        ) 
Example #9
Source File: test_feedgenerator.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rfc2822_date_with_timezone(self):
        """
        rfc2822_date() correctly formats datetime objects with tzinfo.
        """
        self.assertEqual(
            feedgenerator.rfc2822_date(datetime.datetime(2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(60))),
            "Fri, 14 Nov 2008 13:37:00 +0100"
        ) 
Example #10
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_fixedoffset_negative_timedelta(self):
        delta = datetime.timedelta(hours=-2)
        self.assertEqual(timezone.get_fixed_timezone(delta).utcoffset(None), delta) 
Example #11
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_make_aware_no_tz(self):
        self.assertEqual(
            timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30)),
            datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=timezone.get_fixed_timezone(-300))
        ) 
Example #12
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_naturalday_tz(self):
        today = datetime.date.today()
        tz_one = get_fixed_timezone(-720)
        tz_two = get_fixed_timezone(720)

        # Can be today or yesterday
        date_one = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_one)
        naturalday_one = humanize.naturalday(date_one)
        # Can be today or tomorrow
        date_two = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_two)
        naturalday_two = humanize.naturalday(date_two)

        # As 24h of difference they will never be the same
        self.assertNotEqual(naturalday_one, naturalday_two) 
Example #13
Source File: feeds.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def item_pubdate(self, item):
        # Provide a weird offset so that the test can know it's getting this
        # specific offset and not accidentally getting on from
        # settings.TIME_ZONE.
        return item.published.replace(tzinfo=get_fixed_timezone(42)) 
Example #14
Source File: test_time.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_time03(self):
        output = self.engine.render_to_string('time03', {'t': time(4, 0, tzinfo=timezone.get_fixed_timezone(30))})
        self.assertEqual(output, '4 a.m.::::') 
Example #15
Source File: timezone_utils.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.now = datetime.now()
        self.now_tz = timezone.make_aware(
            self.now, timezone.get_default_timezone(),
        )
        self.now_tz_i = timezone.localtime(
            self.now_tz, timezone.get_fixed_timezone(195),
        )
        self.today = date.today() 
Example #16
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_different_timezones(self):
        """ When using two different timezones. """
        now = datetime.datetime.now()
        now_tz = timezone.make_aware(now, timezone.get_default_timezone())
        now_tz_i = timezone.localtime(now_tz, timezone.get_fixed_timezone(195))

        self.assertEqual(timesince(now), '0\xa0minutes')
        self.assertEqual(timesince(now_tz), '0\xa0minutes')
        self.assertEqual(timesince(now_tz_i), '0\xa0minutes')
        self.assertEqual(timesince(now_tz, now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz, now_tz_i), '0\xa0minutes') 
Example #17
Source File: test_feedgenerator.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rfc3339_date_with_timezone(self):
        """
        rfc3339_date() correctly formats datetime objects with tzinfo.
        """
        self.assertEqual(
            feedgenerator.rfc3339_date(datetime.datetime(2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(120))),
            "2008-11-14T13:37:00+02:00"
        ) 
Example #18
Source File: dateparse.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def parse_datetime(value):
    """Parses 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(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        tzinfo = kw.pop('tzinfo')
        if tzinfo == 'Z':
            tzinfo = utc
        elif tzinfo is not None:
            offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
            offset = 60 * int(tzinfo[1:3]) + offset_mins
            if tzinfo[0] == '-':
                offset = -offset
            tzinfo = get_fixed_timezone(offset)
        kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}
        kw['tzinfo'] = tzinfo
        return datetime.datetime(**kw) 
Example #19
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_fixedoffset_negative_timedelta(self):
        delta = datetime.timedelta(hours=-2)
        self.assertEqual(timezone.get_fixed_timezone(delta).utcoffset(''), delta) 
Example #20
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_fixedoffset_timedelta(self):
        delta = datetime.timedelta(hours=1)
        self.assertEqual(timezone.get_fixed_timezone(delta).utcoffset(''), delta) 
Example #21
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_make_aware_no_tz(self):
        self.assertEqual(
            timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30)),
            datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=timezone.get_fixed_timezone(-300))
        ) 
Example #22
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_naturalday_tz(self):
        today = datetime.date.today()
        tz_one = get_fixed_timezone(-720)
        tz_two = get_fixed_timezone(720)

        # Can be today or yesterday
        date_one = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_one)
        naturalday_one = humanize.naturalday(date_one)
        # Can be today or tomorrow
        date_two = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_two)
        naturalday_two = humanize.naturalday(date_two)

        # As 24h of difference they will never be the same
        self.assertNotEqual(naturalday_one, naturalday_two) 
Example #23
Source File: dateparse.py    From python2017 with MIT License 5 votes vote down vote up
def parse_datetime(value):
    """Parses 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(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        tzinfo = kw.pop('tzinfo')
        if tzinfo == 'Z':
            tzinfo = utc
        elif tzinfo is not None:
            offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
            offset = 60 * int(tzinfo[1:3]) + offset_mins
            if tzinfo[0] == '-':
                offset = -offset
            tzinfo = get_fixed_timezone(offset)
        kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}
        kw['tzinfo'] = tzinfo
        return datetime.datetime(**kw) 
Example #24
Source File: dateparse.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def parse_datetime(value):
    """Parses 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(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        tzinfo = kw.pop('tzinfo')
        if tzinfo == 'Z':
            tzinfo = utc
        elif tzinfo is not None:
            offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
            offset = 60 * int(tzinfo[1:3]) + offset_mins
            if tzinfo[0] == '-':
                offset = -offset
            tzinfo = get_fixed_timezone(offset)
        kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}
        kw['tzinfo'] = tzinfo
        return datetime.datetime(**kw) 
Example #25
Source File: utils.py    From django-cockroachdb with Apache License 2.0 5 votes vote down vote up
def utc_tzinfo_factory(offset):
    if offset != 0:
        return get_fixed_timezone(offset)
    return utc 
Example #26
Source File: dateparse.py    From python with Apache License 2.0 5 votes vote down vote up
def parse_datetime(value):
    """Parses 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(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        tzinfo = kw.pop('tzinfo')
        if tzinfo == 'Z':
            tzinfo = utc
        elif tzinfo is not None:
            offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
            offset = 60 * int(tzinfo[1:3]) + offset_mins
            if tzinfo[0] == '-':
                offset = -offset
            tzinfo = get_fixed_timezone(offset)
        kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}
        kw['tzinfo'] = tzinfo
        return datetime.datetime(**kw) 
Example #27
Source File: date.py    From graphene-django-extras with MIT License 5 votes vote down vote up
def _format_time_ago(dt, now=None, full=False, ago_in=False, two_days=False):

    if not isinstance(dt, timedelta):
        if now is None:
            now = timezone.localtime(
                timezone=timezone.get_fixed_timezone(-int(t.timezone / 60))
            )

        original_dt = dt
        dt = _parse(dt)
        now = _parse(now)

        if dt is None:
            raise ValueError(
                "The parameter `dt` should be datetime timedelta, or datetime formatted string."
            )
        if now is None:
            raise ValueError(
                "the parameter `now` should be datetime, or datetime formatted string."
            )

        result = relativedelta.relativedelta(dt, now)
        flag, result = _format_relativedelta(result, full, two_days, original_dt)
        if ago_in and flag is not None:
            result = "in {}".format(result) if flag else "{} ago".format(result)
        return result 
Example #28
Source File: test_serialize.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_serialise_with_aware_datetime(self):
        """
        This tests that aware datetimes are converted to as UTC
        """
        # make an aware datetime, consisting of WAGTAIL_05_RELEASE_DATETIME
        # in a timezone 1hr west of UTC
        one_hour_west = timezone.get_fixed_timezone(-60)

        local_time = timezone.make_aware(self.WAGTAIL_05_RELEASE_DATETIME, one_hour_west)
        log = Log(time=local_time, data="Wagtail 0.5 released")
        log_json = json.loads(log.to_json())

        # Now check that the time is stored correctly with the timezone information at the end
        self.assertEqual(log_json['time'], '2014-08-01T12:01:42Z') 
Example #29
Source File: dateparse.py    From bioforum with MIT License 5 votes vote down vote up
def parse_datetime(value):
    """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.

    Raise ValueError if the input is well formatted but not a valid datetime.
    Return None if the input isn't well formatted.
    """
    match = datetime_re.match(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        tzinfo = kw.pop('tzinfo')
        if tzinfo == 'Z':
            tzinfo = utc
        elif tzinfo is not None:
            offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
            offset = 60 * int(tzinfo[1:3]) + offset_mins
            if tzinfo[0] == '-':
                offset = -offset
            tzinfo = get_fixed_timezone(offset)
        kw = {k: int(v) for k, v in kw.items() if v is not None}
        kw['tzinfo'] = tzinfo
        return datetime.datetime(**kw) 
Example #30
Source File: jvn.py    From exist with MIT License 4 votes vote down vote up
def insertVuln(self, item, detail, vendor_list, product_list, ref_list, cvss_list, nvd_list):
        logger.info("insertVuln  " + item.get('sec:identifier'))

        try:
            query = Vuln(
                id = item.get('sec:identifier'),
                title = item.get('title'),
                description = item.get('description'),
                vulndb_published_date = datetime.strptime(item.get('dc:date'), '%Y-%m-%dT%H:%M:%S+09:00').replace(tzinfo=tzone.get_fixed_timezone(540)),
                vulndb_last_modified = datetime.strptime(item.get('dcterms:modified'), '%Y-%m-%dT%H:%M:%S+09:00').replace(tzinfo=tzone.get_fixed_timezone(540)),
                disclosure_date = datetime.strptime(item.get('dcterms:issued'), '%Y-%m-%dT%H:%M:%S+09:00').replace(tzinfo=tzone.get_fixed_timezone(540)),
                solution = detail['Solution']['SolutionItem']['Description'],
                impact = detail['Impact']['ImpactItem']['Description'],
                link = item.get('link'),
                source = self.ID,
            )
        except Exception as e:
            logger.error(e)

        #self.printQuery(query)
        self.saveQuery(query)

        for vendor in vendor_list:
            try:
                vendor_obj = self.insertVendor(vendor)
                query.vendors.add(vendor_obj)
            except Exception as e:
                logger.error(e)

        for product in product_list:
            try:
                product_obj = self.insertProduct(product)
                query.products.add(product_obj)
            except Exception as e:
                logger.error(e)

        for ref in ref_list:
            try:
                ref_obj = self.insertRef(ref)
                query.references.add(ref_obj)
            except Exception as e:
                logger.error(e)

        for nvd in nvd_list:
            try:
                nvd_obj = self.insertNvd(nvd)
                query.nvds.add(nvd_obj)
            except Exception as e:
                logger.error(e)

        for cvss in cvss_list:
            try:
                cvss_obj = self.insertCvss(cvss)
                query.cvsses.add(cvss_obj)
            except Exception as e:
                logger.error(e)