How to use pytz - 10 common examples

To help you get started, we’ve selected a few pytz examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github movermeyer / backports.datetime_fromisoformat / tests / tests.py View on Github external
def test_fromisoformat_timespecs(self):
        if sys.version_info >= (3, 6):
            datetime_bases = [
                (2009, 12, 4, 8, 17, 45, 123456),
                (2009, 12, 4, 8, 17, 45, 0)]

            tzinfos = [None, pytz.utc,
                       pytz.FixedOffset(-5 * 60),
                       pytz.FixedOffset(2 * 60),
                       pytz.FixedOffset(6 * 60 + 27)]

            timespecs = ['hours', 'minutes', 'seconds', 'milliseconds', 'microseconds']

            for ip, ts in enumerate(timespecs):
                for tzi in tzinfos:
                    for dt_tuple in datetime_bases:
                        if ts == 'milliseconds':
                            new_microseconds = 1000 * (dt_tuple[6] // 1000)
                            dt_tuple = dt_tuple[0:6] + (new_microseconds,)

                        dt = datetime(*(dt_tuple[0:(4 + ip)]), tzinfo=tzi)
                        dtstr = dt.isoformat(timespec=ts)
                        with self.subTest(dtstr=dtstr):
                            dt_rt = datetime.fromisoformat(dtstr)
                            self.assertEqual(dt, dt_rt)
github iago1460 / django-radio / radioco / apps / schedules / tests.py View on Github external
def test_rearrenge_episodes_new_schedule(self):
        Schedule.objects.create(
            programme=self.programme,
            schedule_board=ScheduleBoard.objects.create(),
            type="L",
            recurrences= recurrence.Recurrence(
                dtstart=datetime.datetime(2015, 1, 3, 16, 0, 0),
                dtend=datetime.datetime(2015, 1, 31, 16, 0, 0),
                rrules=[recurrence.Rule(recurrence.WEEKLY)]))

        utils.rearrange_episodes(self.programme, pytz.utc.localize(datetime.datetime(2015, 1, 1)))
        self.assertListEqual(
            map(lambda e: e.issue_date, self.programme.episode_set.all().order_by('issue_date')[:5]),
            [
                datetime.datetime(2015, 1, 1, 14, 0),
                datetime.datetime(2015, 1, 2, 14, 0),
                datetime.datetime(2015, 1, 3, 14, 0),
                datetime.datetime(2015, 1, 3, 16, 0),
                datetime.datetime(2015, 1, 4, 14, 0)
            ]
github openeemeter / eemeter / tests / structures / test_intervention.py View on Github external
def test_ok_start_only():
    intervention = Intervention(datetime(2000, 1, 1, tzinfo=pytz.UTC))
    assert intervention.start_date == datetime(2000, 1, 1, tzinfo=pytz.UTC)
    assert intervention.end_date is None
github inducer / relate / tests / test_models.py View on Github external
def test_last_activity(self):
        fs = factories.FlowSessionFactory(participation=self.participation)
        fpdata = factories.FlowPageDataFactory(flow_session=fs)
        factories.FlowPageVisitFactory(
            page_data=fpdata, answer=None,
            visit_time=datetime(2019, 1, 1, tzinfo=pytz.UTC)
        )
        factories.FlowPageVisitFactory(
            page_data=fpdata, answer=None,
            visit_time=datetime(2019, 1, 2, tzinfo=pytz.UTC)
        )
        self.assertEqual(fs.last_activity(), None)

        fpv = factories.FlowPageVisitFactory(
            page_data=fpdata, answer={"answer": "hi"},
            visit_time=datetime(2018, 12, 31, tzinfo=pytz.UTC)
        )

        self.assertEqual(fs.last_activity(), fpv.visit_time)
github opentok / Opentok-Python-SDK / tests / test_archive_api.py View on Github external
expect(httpretty.last_request().headers[u('content-type')]).to(equal(u('application/json')))
        # non-deterministic json encoding. have to decode to test it properly
        if PY2:
            body = json.loads(httpretty.last_request().body)
        if PY3:
            body = json.loads(httpretty.last_request().body.decode('utf-8'))
        expect(body).to(have_key(u('sessionId'), u('SESSIONID')))
        expect(body).to(have_key(u('name'), u('ARCHIVE NAME')))
        expect(archive).to(be_an(Archive))
        expect(archive).to(have_property(u('id'), u('30b3ebf1-ba36-4f5b-8def-6f70d9986fe9')))
        expect(archive).to(have_property(u('name'), ('ARCHIVE NAME')))
        expect(archive).to(have_property(u('status'), u('started')))
        expect(archive).to(have_property(u('session_id'), u('SESSIONID')))
        expect(archive).to(have_property(u('partner_id'), 123456))
        if PY2:
            created_at = datetime.datetime.fromtimestamp(1395183243, pytz.UTC)
        if PY3:
            created_at = datetime.datetime.fromtimestamp(1395183243, datetime.timezone.utc)
        expect(archive).to(have_property(u('created_at'), equal(created_at)))
        expect(archive).to(have_property(u('size'), equal(0)))
        expect(archive).to(have_property(u('duration'), equal(0)))
        expect(archive).to(have_property(u('url'), equal(None)))
github openeemeter / eemeter / tests / modeling / test_caltrack_formatter.py View on Github external
def daily_trace():
    data = {"value": np.ones(60) * 1}
    columns = ["value", "estimated"]
    index = pd.date_range('2000-01-01', periods=60, freq='D', tz=pytz.UTC)
    df = pd.DataFrame(data, index=index, columns=columns)
    return EnergyTrace("ELECTRICITY_CONSUMPTION_SUPPLIED", df, unit="KWH")
github AuHau / toggl-cli / tests.py View on Github external
def test_stop_complex(self):
        # start an entry now
        self.entry = toggl.TimeEntry(description=desc('stop2'))
        self.entry.start()

        # find it
        entry = self.find_time_entry(desc('stop2'))
        self.assertIsNotNone(entry)
        
        # stop it an hour from now
        one_hour_ahead = pytz.UTC.localize(datetime.datetime.utcnow() + datetime.timedelta(hours=1))
        entry.stop(one_hour_ahead)

        # find it again
        entry = self.find_time_entry(desc('stop2'))
        self.assertIsNotNone(entry)

        # make sure duration is at least 1 hour (3600 seconds)
        self.assertGreaterEqual(entry.get('duration'), 3600)
github dirn / When.py / tests / test_when.py View on Github external
def test_common_timezones(self):
        """Test when.common_timezones()"""
        # Make sure common_timezones() matches pytz's version
        common_timezones = when.common_timezones()
        self.assertEqual(common_timezones, pytz.common_timezones)
github wtolson / pysis / tests / test_labels.py View on Github external
assert label['time1'] == datetime.time(12)

    assert isinstance(label['time_s'], datetime.time)
    assert label['time_s'] == datetime.time(12, 0, 45)

    assert isinstance(label['time_s_float'], datetime.time)
    assert label['time_s_float'] == datetime.time(12, 0, 45, 457100)

    assert isinstance(label['time_tz1'], datetime.time)
    assert label['time_tz1'] == datetime.time(15, 24, 12, tzinfo=pytz.utc)

    assert isinstance(label['time_tz2'], datetime.time)
    assert label['time_tz2'] == datetime.time(1, 12, 22, tzinfo=pytz.FixedOffset(420))  # noqa

    assert isinstance(label['time_tz3'], datetime.time)
    assert label['time_tz3'] == datetime.time(1, 12, 22, tzinfo=pytz.FixedOffset(420))  # noqa

    assert isinstance(label['time_tz4'], datetime.time)
    assert label['time_tz4'] == datetime.time(1, 10, 39, 457500, pytz.FixedOffset(420))  # noqa

    assert isinstance(label['datetime1'], datetime.datetime)
    assert label['datetime1'] == datetime.datetime(1990, 7, 4, 12)

    assert isinstance(label['datetime2'], datetime.datetime)
    assert label['datetime2'] == datetime.datetime(1990, 6, 7, 15, 24, 12, tzinfo=pytz.utc)  # noqa

    assert isinstance(label['datetime3'], datetime.datetime)
    assert label['datetime3'] == datetime.datetime(2001, 1, 1, 1, 10, 39, tzinfo=pytz.FixedOffset(420))  # noqa

    assert isinstance(label['datetime4'], datetime.datetime)
    assert label['datetime4'] == datetime.datetime(2001, 1, 1, 1, 10, 39, 457591, pytz.FixedOffset(420))  # noqa
github mvantellingen / python-zeep / tests / test_xsd_builtins.py View on Github external
def test_pythonvalue(self):
        instance = builtins.gMonth()
        assert instance.pythonvalue("--05") == (5, None)
        assert instance.pythonvalue("--11Z") == (11, pytz.utc)
        assert instance.pythonvalue("--11+02:00") == (11, pytz.FixedOffset(120))
        assert instance.pythonvalue("--11-04:00") == (11, pytz.FixedOffset(-240))
        assert instance.pythonvalue("--11") == (11, None)
        assert instance.pythonvalue("--02") == (2, None)

        with pytest.raises(builtins.ParseError):
            assert instance.pythonvalue("99")