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

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

项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_NaT_methods(self):
        # GH 9513
        raise_methods = ['astimezone', 'combine', 'ctime', 'dst',
                         'fromordinal', 'fromtimestamp', 'isocalendar',
                         'strftime', 'strptime', 'time', 'timestamp',
                         'timetuple', 'timetz', 'toordinal', 'tzname',
                         'utcfromtimestamp', 'utcnow', 'utcoffset',
                         'utctimetuple']
        nat_methods = ['date', 'now', 'replace', 'to_datetime', 'today']
        nan_methods = ['weekday', 'isoweekday']

        for method in raise_methods:
            if hasattr(NaT, method):
                self.assertRaises(ValueError, getattr(NaT, method))

        for method in nan_methods:
            if hasattr(NaT, method):
                self.assertTrue(np.isnan(getattr(NaT, method)()))

        for method in nat_methods:
            if hasattr(NaT, method):
                self.assertIs(getattr(NaT, method)(), NaT)

        # GH 12300
        self.assertEqual(NaT.isoformat(), 'NaT')
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_class_ops_pytz(self):
        tm._skip_if_no_pytz()
        from pytz import timezone

        def compare(x, y):
            self.assertEqual(int(Timestamp(x).value / 1e9),
                             int(Timestamp(y).value / 1e9))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(timezone('UTC')))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_class_ops_dateutil(self):
        tm._skip_if_no_dateutil()
        from dateutil.tz import tzutc

        def compare(x, y):
            self.assertEqual(int(np.round(Timestamp(x).value / 1e9)),
                             int(np.round(Timestamp(y).value / 1e9)))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(tzutc()))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_utcfromtimestamp(self):
        import time

        ts = time.time()
        expected = time.gmtime(ts)
        got = self.theclass.utcfromtimestamp(ts)
        self.verify_field_equality(expected, got)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_insane_utcfromtimestamp(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for insane in -1e200, 1e200:
            self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
                              insane)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_negative_float_utcfromtimestamp(self):
        d = self.theclass.utcfromtimestamp(-1.05)
        self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_utcnow(self):
        import time

        # Call it a success if utcnow() and utcfromtimestamp() are within
        # a second of each other.
        tolerance = timedelta(seconds=1)
        for dummy in range(3):
            from_now = self.theclass.utcnow()
            from_timestamp = self.theclass.utcfromtimestamp(time.time())
            if abs(from_timestamp - from_now) <= tolerance:
                break
            # Else try again a few times.
        self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_tzinfo_fromtimestamp(self):
        import time
        meth = self.theclass.fromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(ts, off42)
        again = meth(ts, tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, ts, 16)
        self.assertRaises(TypeError, meth, ts, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, ts, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, ts, off42, off42)
        # Too few args.
        self.assertRaises(TypeError, meth)

        # Try to make sure tz= actually does some conversion.
        timestamp = 1000000000
        utcdatetime = datetime.utcfromtimestamp(timestamp)
        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
        # But on some flavor of Mac, it's nowhere near that.  So we can't have
        # any idea here what time that actually is, we can only test that
        # relative changes match.
        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
        tz = FixedOffset(utcoffset, "tz", 0)
        expected = utcdatetime + utcoffset
        got = datetime.fromtimestamp(timestamp, tz)
        self.assertEqual(expected, got.replace(tzinfo=None))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_utcfromtimestamp(self):
        import time

        ts = time.time()
        expected = time.gmtime(ts)
        got = self.theclass.utcfromtimestamp(ts)
        self.verify_field_equality(expected, got)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_insane_utcfromtimestamp(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for insane in -1e200, 1e200:
            self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
                              insane)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_negative_float_utcfromtimestamp(self):
        d = self.theclass.utcfromtimestamp(-1.05)
        self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_utcnow(self):
        import time

        # Call it a success if utcnow() and utcfromtimestamp() are within
        # a second of each other.
        tolerance = timedelta(seconds=1)
        for dummy in range(3):
            from_now = self.theclass.utcnow()
            from_timestamp = self.theclass.utcfromtimestamp(time.time())
            if abs(from_timestamp - from_now) <= tolerance:
                break
            # Else try again a few times.
        self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_tzinfo_fromtimestamp(self):
        import time
        meth = self.theclass.fromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(ts, off42)
        again = meth(ts, tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, ts, 16)
        self.assertRaises(TypeError, meth, ts, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, ts, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, ts, off42, off42)
        # Too few args.
        self.assertRaises(TypeError, meth)

        # Try to make sure tz= actually does some conversion.
        timestamp = 1000000000
        utcdatetime = datetime.utcfromtimestamp(timestamp)
        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
        # But on some flavor of Mac, it's nowhere near that.  So we can't have
        # any idea here what time that actually is, we can only test that
        # relative changes match.
        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
        tz = FixedOffset(utcoffset, "tz", 0)
        expected = utcdatetime + utcoffset
        got = datetime.fromtimestamp(timestamp, tz)
        self.assertEqual(expected, got.replace(tzinfo=None))
项目:mhacks-admin    作者:mhacks    | 项目源码 | 文件源码
def to_internal_value(self, value):
        from datetime import datetime
        from pytz import utc
        try:
            return datetime.utcfromtimestamp(float(value)).replace(tzinfo=utc)
        except ValueError:
            self.fail('invalid', format='Unix Epoch Timestamp')
项目:mhacks-admin    作者:mhacks    | 项目源码 | 文件源码
def parse_date_last_updated(request):
    date_last_updated_raw = request.query_params.get('since', None)
    if date_last_updated_raw:
        try:
            from pytz import utc
            from datetime import datetime
            return datetime.utcfromtimestamp(float(date_last_updated_raw)).replace(tzinfo=utc)
        except ValueError:
            print('Value error')
            pass
    return None
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_utcfromtimestamp(self):
        import time

        ts = time.time()
        expected = time.gmtime(ts)
        got = self.theclass.utcfromtimestamp(ts)
        self.verify_field_equality(expected, got)
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_insane_utcfromtimestamp(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for insane in -1e200, 1e200:
            self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
                              insane)
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_negative_float_utcfromtimestamp(self):
        d = self.theclass.utcfromtimestamp(-1.05)
        self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_utcnow(self):
        import time

        # Call it a success if utcnow() and utcfromtimestamp() are within
        # a second of each other.
        tolerance = timedelta(seconds=1)
        for dummy in range(3):
            from_now = self.theclass.utcnow()
            from_timestamp = self.theclass.utcfromtimestamp(time.time())
            if abs(from_timestamp - from_now) <= tolerance:
                break
            # Else try again a few times.
        self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_tzinfo_fromtimestamp(self):
        import time
        meth = self.theclass.fromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(ts, off42)
        again = meth(ts, tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, ts, 16)
        self.assertRaises(TypeError, meth, ts, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, ts, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, ts, off42, off42)
        # Too few args.
        self.assertRaises(TypeError, meth)

        # Try to make sure tz= actually does some conversion.
        timestamp = 1000000000
        utcdatetime = datetime.utcfromtimestamp(timestamp)
        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
        # But on some flavor of Mac, it's nowhere near that.  So we can't have
        # any idea here what time that actually is, we can only test that
        # relative changes match.
        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
        tz = FixedOffset(utcoffset, "tz", 0)
        expected = utcdatetime + utcoffset
        got = datetime.fromtimestamp(timestamp, tz)
        self.assertEqual(expected, got.replace(tzinfo=None))
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_utcfromtimestamp(self):
        import time

        ts = time.time()
        expected = time.gmtime(ts)
        got = self.theclass.utcfromtimestamp(ts)
        self.verify_field_equality(expected, got)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_insane_utcfromtimestamp(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for insane in -1e200, 1e200:
            self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
                              insane)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_negative_float_utcfromtimestamp(self):
        d = self.theclass.utcfromtimestamp(-1.05)
        self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_utcnow(self):
        import time

        # Call it a success if utcnow() and utcfromtimestamp() are within
        # a second of each other.
        tolerance = timedelta(seconds=1)
        for dummy in range(3):
            from_now = self.theclass.utcnow()
            from_timestamp = self.theclass.utcfromtimestamp(time.time())
            if abs(from_timestamp - from_now) <= tolerance:
                break
            # Else try again a few times.
        self.assertTrue(abs(from_timestamp - from_now) <= tolerance)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_tzinfo_fromtimestamp(self):
        import time
        meth = self.theclass.fromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(ts, off42)
        again = meth(ts, tz=off42)
        self.assertTrue(another.tzinfo is again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, ts, 16)
        self.assertRaises(TypeError, meth, ts, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, ts, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, ts, off42, off42)
        # Too few args.
        self.assertRaises(TypeError, meth)

        # Try to make sure tz= actually does some conversion.
        timestamp = 1000000000
        utcdatetime = datetime.utcfromtimestamp(timestamp)
        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
        # But on some flavor of Mac, it's nowhere near that.  So we can't have
        # any idea here what time that actually is, we can only test that
        # relative changes match.
        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
        tz = FixedOffset(utcoffset, "tz", 0)
        expected = utcdatetime + utcoffset
        got = datetime.fromtimestamp(timestamp, tz)
        self.assertEqual(expected, got.replace(tzinfo=None))
项目:helios-server-mixnet    作者:RunasSudo    | 项目源码 | 文件源码
def process_response(self, request, response):
        if not self.internal and request.facebook.session_key and request.facebook.uid:
            request.session['facebook_session_key'] = request.facebook.session_key
            request.session['facebook_user_id'] = request.facebook.uid

            if request.facebook.session_key_expires:
                expiry = datetime.datetime.fromtimestamp(request.facebook.session_key_expires)
                request.session.set_expiry(expiry)

        try:
            fb = request.facebook
        except:
            return response

        if not fb.is_session_from_cookie:
            # Make sure the browser accepts our session cookies inside an Iframe
            response['P3P'] = 'CP="NOI DSP COR NID ADMa OPTa OUR NOR"'
            fb_cookies = {
                'expires': fb.session_key_expires,
                'session_key': fb.session_key,
                'user': fb.uid,
            }

            expire_time = None
            if fb.session_key_expires:
                expire_time = datetime.utcfromtimestamp(fb.session_key_expires)

            for k in fb_cookies:
                response.set_cookie(self.api_key + '_' + k, fb_cookies[k], expires=expire_time)
            response.set_cookie(self.api_key , fb._hash_args(fb_cookies), expires=expire_time)

        return response
项目:hazdev-gis    作者:usgs    | 项目源码 | 文件源码
def getEvents(magnitude=1.0,significance=0,product='shakemap',lastUpdate=2678000):
    """
    Return a list of earthquake event urls that meet the conditions set above.
    Inputs:

     * magnitude: Event magnitude (OR condition with significance)
     * significance: Event significance (integer score assembled from weighting magnitude, PAGER alert level, Max MMI, etc.)
     * lastUpdateDelta: Only retrieve events that have been updated in the past lastUpdate minutes.
     * product: Only retrieve events that have this product type associated with them.
    """
    fh = urllib2.urlopen(FEEDURL)
    data = fh.read()
    fh.close()
    jdict = json.loads(data)
    eventurls = []
    tnow = datetime.utcnow()
    for event in jdict['features']:
        eurl = event['properties']['detail']
        emag = event['properties']['mag']
        esig = event['properties']['sig']
        etypes = event['properties']['types'].split(',')[1:-1]
        eupdate = datetime.utcfromtimestamp(event['properties']['updated']/1000)
        hasproduct = product in etypes
        if not hasproduct:
            continue
        if eupdate < tnow - timedelta(seconds=60*lastUpdate):
            continue
        eventurls.append(eurl)
    return eventurls
项目:hazdev-gis    作者:usgs    | 项目源码 | 文件源码
def getEvents(magnitude=1.0,significance=0,product='dyfi',lastUpdate=2678000):
    """
    Return a list of earthquake event urls that meet the conditions set above.
    Inputs:

     * magnitude: Event magnitude (OR condition with significance)
     * significance: Event significance (integer score assembled from weighting magnitude, PAGER alert level, Max MMI, etc.)
     * lastUpdateDelta: Only retrieve events that have been updated in the past lastUpdate minutes.
     * product: Only retrieve events that have this product type associated with them.
    """
    fh = urllib2.urlopen(FEEDURL)
    data = fh.read()
    fh.close()
    jdict = json.loads(data)
    eventurls = []
    tnow = datetime.utcnow()
    for event in jdict['features']:
        eurl = event['properties']['detail']
        emag = event['properties']['mag']
        esig = event['properties']['sig']
        etypes = event['properties']['types'].split(',')[1:-1]
        eupdate = datetime.utcfromtimestamp(event['properties']['updated']/1000)
        hasproduct = product in etypes
        if not hasproduct:
            continue
        if eupdate < tnow - timedelta(seconds=60*lastUpdate):
            continue
        eventurls.append(eurl)
    return eventurls
项目:hazdev-gis    作者:usgs    | 项目源码 | 文件源码
def getEvents(magnitude=1.0,significance=0,product='origin',lastUpdate=2678000):
    """
    Return a list of earthquake event urls that meet the conditions set above.
    Inputs:

     * magnitude: Event magnitude (OR condition with significance)
     * significance: Event significance (integer score assembled from weighting magnitude, PAGER alert level, Max MMI, etc.)
     * lastUpdateDelta: Only retrieve events that have been updated in the past lastUpdate minutes.
     * product: Only retrieve events that have this product type associated with them.
    """
    fh = urllib2.urlopen(FEEDURL)
    data = fh.read()
    fh.close()
    jdict = json.loads(data)
    eventurls = []
    tnow = datetime.utcnow()
    for event in jdict['features']:
        eurl = event['properties']['detail']
        emag = event['properties']['mag']
        esig = event['properties']['sig']
        etypes = event['properties']['types'].split(',')[1:-1]
        eupdate = datetime.utcfromtimestamp(event['properties']['updated']/1000)
        hasproduct = product in etypes
        if not hasproduct:
            continue
        if eupdate < tnow - timedelta(seconds=60*lastUpdate):
            continue
        eventurls.append(eurl)
    return eventurls