Python datetime.utcfromtimestamp() Examples
The following are 30
code examples of datetime.utcfromtimestamp().
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
datetime
, or try the search function
.
Example #1
Source File: sunposition.py From sun-position with MIT License | 6 votes |
def julian_day(dt): """Convert UTC datetimes or UTC timestamps to Julian days Parameters ---------- dt : array_like UTC datetime objects or UTC timestamps (as per datetime.utcfromtimestamp) Returns ------- jd : ndarray datetimes converted to fractional Julian days """ dts = np.array(dt) if len(dts.shape) == 0: return _sp.julian_day(dt) jds = np.empty(dts.shape) for i,d in enumerate(dts.flat): jds.flat[i] = _sp.julian_day(d) return jds
Example #2
Source File: leaves.py From zschema with Apache License 2.0 | 6 votes |
def _validate(self, name, value, path=_NO_ARG): try: if isinstance(value, datetime.datetime): dt = value elif isinstance(value, int): dt = datetime.datetime.utcfromtimestamp(value) else: dt = dateutil.parser.parse(value) except (ValueError, TypeError): # Either `datetime.utcfromtimestamp` or `dateutil.parser.parse` above # may raise on invalid input. m = "%s: %s is not valid timestamp" % (name, str(value)) raise DataValidationException(m, path=path) dt = DateTime._ensure_tz_aware(dt) if dt > self._max_value_dt: m = "%s: %s is greater than allowed maximum (%s)" % (name, str(value), str(self._max_value_dt)) raise DataValidationException(m, path=path) if dt < self._min_value_dt: m = "%s: %s is less than allowed minimum (%s)" % (name, str(value), str(self._min_value_dt)) raise DataValidationException(m, path=path)
Example #3
Source File: test_datetime.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
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)
Example #4
Source File: test_datetime.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #5
Source File: test_datetime.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_negative_float_utcfromtimestamp(self): d = self.theclass.utcfromtimestamp(-1.05) self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
Example #6
Source File: test_datetime.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #7
Source File: test_datetime.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
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))
Example #8
Source File: test_datetime.py From medicare-demo with Apache License 2.0 | 5 votes |
def test_utcfromtimestamp(self): import time ts = time.time() expected = time.gmtime(ts) got = self.theclass.utcfromtimestamp(ts) self.verify_field_equality(expected, got)
Example #9
Source File: test_datetime.py From medicare-demo with Apache License 2.0 | 5 votes |
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)
Example #10
Source File: test_datetime.py From medicare-demo with Apache License 2.0 | 5 votes |
def test_negative_float_utcfromtimestamp(self): # Windows doesn't accept negative timestamps if os.name == "nt": return d = self.theclass.utcfromtimestamp(-1.05) self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
Example #11
Source File: test_datetime.py From medicare-demo with Apache License 2.0 | 5 votes |
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.failUnless(abs(from_timestamp - from_now) <= tolerance)
Example #12
Source File: test_datetime.py From medicare-demo with Apache License 2.0 | 5 votes |
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.failUnless(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))
Example #13
Source File: serializefakeredis.py From conifer with Apache License 2.0 | 5 votes |
def load_redis_dict(self, obj): new_dict = {} redis_type = obj.get('__redis_type') exp = None for key, value in obj.items(): if key == '__redis_type': continue key = key.encode('utf-8') if redis_type == 'exp' and isinstance(value, list): if isinstance(value[1], int): exp = datetime.utcfromtimestamp(value[1]) else: exp = None value = value[0] if isinstance(value, str): value = value.encode('utf-8') elif isinstance(value, list): value = self.load_redis_set(value) elif isinstance(value, dict): value = self.load_redis_dict(value) if redis_type == 'exp': new_dict[key] = (value, exp) else: new_dict[key] = value if redis_type == 'zset': redis_dict = _ZSet() elif redis_type == 'hash': redis_dict = _Hash() elif redis_type == 'exp': redis_dict = _ExpiringDict() else: raise Exception('Invalid redis_dict: ' + str(redis_type)) redis_dict._dict = new_dict return redis_dict
Example #14
Source File: test_datetime.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def test_utcfromtimestamp(self): import time ts = time.time() expected = time.gmtime(ts) got = self.theclass.utcfromtimestamp(ts) self.verify_field_equality(expected, got)
Example #15
Source File: models.py From archon with MIT License | 5 votes |
def conv_timestamp(ts, exchange): target_format = '%Y-%m-%dT%H:%M:%S' if exchange==exc.CRYPTOPIA: #local = pytz.timezone("Europe/London") #tsf = datetime.datetime.fromtimestamp(ts) tsf = datetime.datetime.utcfromtimestamp(ts) #local_dt = local.localize(tsf, is_dst=None) utc_dt = tsf.astimezone(pytz.utc) utc_dt = utc_dt + datetime.timedelta(hours=4) #dt = utc_dt.strftime(date_broker_format) tsf = utc_dt.strftime(target_format) return tsf elif exchange==exc.BITTREX: ts = ts.split('.')[0] tsf = datetime.datetime.strptime(ts,'%Y-%m-%dT%H:%M:%S') utc=pytz.UTC utc_dt = tsf.astimezone(pytz.utc) utc_dt = utc_dt + datetime.timedelta(hours=4) tsf = utc_dt.strftime(target_format) return tsf elif exchange==exc.KUCOIN: #dt = conv_timestamp(t/1000,exchange) tsf = datetime.datetime.utcfromtimestamp(ts/1000) #tsf = datetime.datetime.strptime(ts,'%Y-%m-%dT%H:%M:%S') utc=pytz.UTC utc_dt = tsf.astimezone(pytz.utc) utc_dt = utc_dt + datetime.timedelta(hours=4) #tsf = utc_dt.strftime() tsf = utc_dt.strftime(target_format) return tsf elif exchange==exc.BINANCE: tsf = datetime.datetime.utcfromtimestamp(int(ts/1000)) utc=pytz.UTC utc_dt = tsf.astimezone(pytz.utc) utc_dt = utc_dt + datetime.timedelta(hours=4) tsf = utc_dt.strftime(target_format) return tsf
Example #16
Source File: test_datetime.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def test_negative_float_utcfromtimestamp(self): d = self.theclass.utcfromtimestamp(-1.05) self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
Example #17
Source File: test_datetime.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
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)
Example #18
Source File: test_datetime.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
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))
Example #19
Source File: monitor.py From ComicStreamer with Apache License 2.0 | 5 votes |
def checkIfRemovedOrModified(self, comic, pathlist): remove = False def inFolderlist(filepath, pathlist): for p in pathlist: if p in filepath: return True return False if not (os.path.exists(comic.path)): # file is missing, remove it from the comic table, add it to deleted table logging.debug(u"Removing missing {0}".format(comic.path)) remove = True elif not inFolderlist(comic.path, pathlist): logging.debug(u"Removing unwanted {0}".format(comic.path)) remove = True else: # file exists. check the mod date. # if it's been modified, remove it, and it'll be re-added #curr = datetime.datetime.fromtimestamp(os.path.getmtime(comic.path)) curr = datetime.utcfromtimestamp(os.path.getmtime(comic.path)) prev = comic.mod_ts if curr != prev: logging.debug(u"Removed modifed {0}".format(comic.path)) remove = True if remove: self.removeComic(comic) self.remove_count += 1
Example #20
Source File: monitor.py From ComicStreamer with Apache License 2.0 | 5 votes |
def getComicMetadata(self, path): #print time.time() - start_time, "seconds" ca = ComicArchive(path, default_image_path=AppFolders.imagePath("default.jpg")) if ca.seemsToBeAComicArchive(): #print >> sys.stdout, u"Adding {0}... \r".format(count), logging.debug(u"Reading in {0} {1}\r".format(self.read_count, path)) sys.stdout.flush() self.read_count += 1 if ca.hasMetadata( MetaDataStyle.CIX ): style = MetaDataStyle.CIX elif ca.hasMetadata( MetaDataStyle.CBI ): style = MetaDataStyle.CBI else: style = None if style is not None: md = ca.readMetadata(style) else: # No metadata in comic. make some guesses from the filename md = ca.metadataFromFilename() md.path = ca.path md.page_count = ca.page_count md.mod_ts = datetime.utcfromtimestamp(os.path.getmtime(ca.path)) md.filesize = os.path.getsize(md.path) md.hash = "" #logging.debug("before hash") #md5 = hashlib.md5() #md5.update(open(md.path, 'r').read()) #md.hash = unicode(md5.hexdigest()) #logging.debug("after hash") return md return None
Example #21
Source File: test_datetime.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def test_utcfromtimestamp(self): import time ts = time.time() expected = time.gmtime(ts) got = self.theclass.utcfromtimestamp(ts) self.verify_field_equality(expected, got)
Example #22
Source File: test_datetime.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
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)
Example #23
Source File: test_datetime.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def test_negative_float_utcfromtimestamp(self): d = self.theclass.utcfromtimestamp(-1.05) self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
Example #24
Source File: test_datetime.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
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)
Example #25
Source File: test_datetime.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
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))
Example #26
Source File: test_datetime.py From BinderFilter with MIT License | 5 votes |
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)
Example #27
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 5 votes |
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)
Example #28
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_negative_float_utcfromtimestamp(self): d = self.theclass.utcfromtimestamp(-1.05) self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
Example #29
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 5 votes |
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)
Example #30
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 5 votes |
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))