我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用time.strptime()。
def main(): #?????????? argvCount = len(sys.argv) #???????????????????????? dateFormat = "%Y-%m-%d %H:%M:%S" dateFormat = "%Y-%m-%d" today = datetime.date.today() if(argvCount == 3): #????????????????????????????????????????? startTime = time.strptime(sys.argv[1],dateFormat) endTime = time.strptime(sys.argv[2],dateFormat) print "startTime:",startTime print "startTime:",endTime custom_report(startTime,endTime) else: #??????2??????????????????? usage()
def history_get(self,item_ID,date_from,date_till): ''' return history of item [eg1]#zabbix_api history_get 23296 "2016-08-01 00:00:00" "2016-09-01 00:00:00" [note]The date_till time must be within the historical data retention time ''' dateFormat = "%Y-%m-%d %H:%M:%S" try: startTime = time.strptime(date_from,dateFormat) endTime = time.strptime(date_till,dateFormat) except: err_msg("???? ['2016-05-01 00:00:00'] ['2016-06-01 00:00:00']") time_from = int(time.mktime(startTime)) time_till = int(time.mktime(endTime)) history_type=self.__item_search(item_ID) self.__history_get(history_type,item_ID,time_from,time_till)
def isoparse(timestring, formats=("%Y-%m-%d %H:%M:%SZ", "%Y-%m-%d %H:%M:%S")): """ >>> isoparse('1970-01-01 00:00:00Z') 0 Also support backwards compatible timestamp format: >>> isoparse('1970-01-01 00:00:00') 0 """ for format in formats: try: time_tuple = time.strptime(timestring, format) except ValueError: continue else: return calendar.timegm(time_tuple) return None
def next_time(time_string): try: parsed = list(time.strptime(time_string, "%H:%M")) except (TypeError, ValueError): return float(time_string) now = time.localtime() current = list(now) current[3:6] = parsed[3:6] current_time = time.time() delta = time.mktime(current) - current_time if delta <= 0.0: current[2] += 1 return time.mktime(current) - current_time return delta
def _parse(): while True: event = yield idiokit.next() for key in event.keys(): event.pop(key, filter=lambda value: not value.strip()) for key in ("ip", "asn", "cc"): event.update(key, _value_split(event.pop(key))) for timestamp in event.pop("first seen"): try: timestamp = time.strftime( "%Y-%m-%d %H:%M:%SZ", time.strptime(timestamp, "%Y-%m-%d %H:%M:%S") ) except ValueError: pass else: event.add("first seen", timestamp) yield idiokit.send(event)
def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: expires = time.time() + morsel['max-age'] elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = time.mktime( time.strptime(morsel['expires'], time_template)) - time.timezone return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, )
def set_day_night_theme(self, dayornight, themename, themefile): ''' Sets a new daynight theme''' currenttimevalue = xbmc.getInfoLabel("Skin.String(SkinHelper.ColorTheme.%s.time)" % dayornight) if not currenttimevalue: currenttimevalue = "20:00" if dayornight == "night" else "07:00" timevalue = xbmcgui.Dialog().input(self.addon.getLocalizedString(32017), currenttimevalue).decode("utf-8") try: # check if the time is valid check_date = datetime(*(time.strptime(timevalue, "%H:%M")[0:6])) del check_date base_setting = "SkinHelper.ColorTheme.%s" % dayornight xbmc.executebuiltin("Skin.SetString(%s.theme,%s)" % (base_setting, themename.encode("utf-8"))) xbmc.executebuiltin("Skin.SetString(%s.time,%s)" % (base_setting, timevalue)) label = "%s (%s %s)" % (themename.encode("utf-8"), self.addon.getLocalizedString(32019), timevalue) xbmc.executebuiltin("Skin.SetString(%s.label,%s)" % (base_setting, label)) xbmc.executebuiltin("Skin.SetString(%s.file,%s)" % (base_setting, themefile.encode("utf-8"))) except Exception as exc: log_exception(__name__, exc) xbmcgui.Dialog().ok(xbmc.getLocalizedString(329), self.addon.getLocalizedString(32018))
def check_daynighttheme(self): '''check if a specific day or night theme should be applied''' if xbmc.getCondVisibility( "Skin.HasSetting(SkinHelper.EnableDayNightThemes) + " "Skin.String(SkinHelper.ColorTheme.Day.time) + " "Skin.String(SkinHelper.ColorTheme.Night.time)"): try: daytime = xbmc.getInfoLabel("Skin.String(SkinHelper.ColorTheme.Day.time)") daytime = datetime(*(time.strptime(daytime, "%H:%M")[0:6])).time() nighttime = xbmc.getInfoLabel("Skin.String(SkinHelper.ColorTheme.Night.time)") nighttime = datetime(*(time.strptime(nighttime, "%H:%M")[0:6])).time() timestamp = datetime.now().time() if daytime <= timestamp <= nighttime: dayornight = "Day" else: dayornight = "Night" current_theme = xbmc.getInfoLabel("Skin.String(SkinHelper.LastColorTheme)") newtheme = xbmc.getInfoLabel("Skin.String(SkinHelper.ColorTheme.%s.theme)" % dayornight) if current_theme != newtheme: themefile = xbmc.getInfoLabel("Skin.String(SkinHelper.ColorTheme.%s.file)" % dayornight) self.load_colortheme(themefile) except Exception as exc: log_exception(__name__, exc)
def istime(value, fmt): """ Return whether or not given value is valid time according to given format. If the value is valid time, this function returns ``True``, otherwise ``False``. Examples:: >>> istime('30 Nov 00', '%d %b %y') True >>> istime('Friday', '%d') False :param value: string to validate time :param fmt: format of time """ try: time_obj = time.strptime(value, fmt) except ValueError: return False return True
def test_global_rules_before(self): ur, br = test_against_global_rules(test_rules, "live", time.strptime("7 59 1", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("2 22 2", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("7 32 5", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("0 23 6", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("5 53 0", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br)
def test_global_rules_for_develop(self): ur, br = test_against_global_rules(test_rules, "develop", time.strptime("7 59 1", "%H %M %w")) self.assertTrue(ur) self.assertFalse(br) ur, br = test_against_global_rules(test_rules, "develop", time.strptime("2 22 2", "%H %M %w")) self.assertTrue(ur) self.assertFalse(br) ur, br = test_against_global_rules(test_rules, "develop", time.strptime("7 32 5", "%H %M %w")) self.assertTrue(ur) self.assertFalse(br) ur, br = test_against_global_rules(test_rules, "develop", time.strptime("0 23 6", "%H %M %w")) self.assertTrue(ur) self.assertFalse(br) ur, br = test_against_global_rules(test_rules, "develop", time.strptime("5 53 0", "%H %M %w")) self.assertTrue(ur) self.assertFalse(br)
def test_global_rules_after(self): ur, br = test_against_global_rules(test_rules, "live", time.strptime("16 01 1", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("14 01 5", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("18 43 4", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("17 01 6", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("18 46 0", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br)
def test_global_rules_inside(self): ur, br = test_against_global_rules(test_rules, "live", time.strptime("14 01 1", "%H %M %w")) self.assertTrue(br) self.assertTrue(ur) ur, br = test_against_global_rules(test_rules, "live", time.strptime("10 59 2", "%H %M %w")) self.assertTrue(br) self.assertTrue(ur) ur, br = test_against_global_rules(test_rules, "live", time.strptime("15 59 4", "%H %M %w")) self.assertTrue(br) self.assertTrue(ur) ur, br = test_against_global_rules(test_rules, "live", time.strptime("13 59 5", "%H %M %w")) self.assertTrue(br) self.assertTrue(ur) ur, br = test_against_global_rules(test_rules, "live", time.strptime("9 46 3", "%H %M %w")) self.assertTrue(br) self.assertTrue(ur)
def test_global_rules_weekend(self): ur, br = test_against_global_rules(test_rules, "live", time.strptime("10 01 6", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("15 45 6", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("8 43 0", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br) ur, br = test_against_global_rules(test_rules, "live", time.strptime("13 22 0", "%H %M %w")) self.assertFalse(ur) self.assertTrue(br)
def test_dtype_with_object(self): # Test using an explicit dtype with an object data = """ 1; 2001-01-01 2; 2002-01-31 """ ndtype = [('idx', int), ('code', np.object)] func = lambda s: strptime(s.strip(), "%Y-%m-%d") converters = {1: func} test = np.genfromtxt(TextIO(data), delimiter=";", dtype=ndtype, converters=converters) control = np.array( [(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))], dtype=ndtype) assert_equal(test, control) ndtype = [('nest', [('idx', int), ('code', np.object)])] try: test = np.genfromtxt(TextIO(data), delimiter=";", dtype=ndtype, converters=converters) except NotImplementedError: pass else: errmsg = "Nested dtype involving objects should be supported." raise AssertionError(errmsg)
def test_transmit_metrics(self, mock_time, mock_socket): mock_socket.side_effect = MockSocket mock_time.return_value = strptime("30 Nov 00", "%d %b %y") testconv = converter.Converter() json_object = json.loads( """{"timestamp" : "975542400", "key":123.0 }""") result = testconv.convert_json_to_flat(json_object, "host.run-name") emitter = CarbonMetricTransmitter() emitter.carbon_port = self.listen_port emitter.transmit_metrics(result, None) self.assertEqual("host.run-name.key 123.0 975542400\n", data[1], data[1])
def test_skip_non_numeric_metrics(self, mock_time, mock_socket): mock_socket.side_effect = MockSocket mock_time.return_value = strptime("30 Nov 00", "%d %b %y") testconv = converter.Converter() json_object = json.loads( """{"timestamp" : "975542400", "key":"value" }""") result = testconv.convert_json_to_flat(json_object, "host.run-name") emitter = CarbonMetricTransmitter() emitter.carbon_port = self.listen_port emitter.transmit_metrics(result, None) self.assertEqual("None.commit-marker 975542400 975542400\n", data[1], data[1])
def checkDates(pDates) : """ check date integrity""" lIndex = 0 #Contrôle la cohérences des dates et l'ordre chronologique de celle-ci try : lOldTime = None for lDate in pDates : lIndex = lIndex + 1 # lTime = time.strptime("%d-%d-%d"%(lDate[ANNEE], lDate[MOIS], lDate[JOUR]), "%Y-%m-%d") if lOldTime and lDate < lOldTime : raise AttributeError("Les dates doivent être dans l'ordre chronologique", pDates) lOldTime = lDate except ValueError : if lIndex == 1 : raise AttributeError("La première date donnée n'est pas cohérente", pDates) else : raise AttributeError("La %dème date donnée n'est pas cohérente" % lIndex, pDates) return pDates
def _date_to_dates(self, source, date_only=False, duau=False): result_data = time.strptime(source, "%Y-%m-%d %H:%M:%S") day = result_data.tm_mday if day == 1: day = '1er' art = '' if not duau: art = 'Le ' result = art + str(day) + ' '\ + MONTH[result_data.tm_mon-1] + ' ' \ + str(result_data.tm_year) if not date_only: result += (' à '+ str(result_data.tm_hour) + 'h' + \ str(result_data.tm_min)) return result
def UpdateDevice(Unit, nValue, sValue, updEvery=False): # Make sure that the Domoticz device still exists (they can be deleted) before updating it if (Unit in Devices): if (Devices[Unit].nValue != nValue) or (Devices[Unit].sValue != sValue): Devices[Unit].Update(nValue, str(sValue)) #Domoticz.Debug("Update "+str(nValue)+":'"+str(sValue)+"' ("+Devices[Unit].Name+")") elif updEvery: # Update device even not changed every X minutes - for Temp and Volt values updMinutes = 15 Domoticz.Debug("LastUpdate: '" + Devices[Unit].LastUpdate + "' ("+Devices[Unit].Name+")") #devUpdate = datetime.strptime("2017-06-22 18:24:21", "%Y-%m-%d %H:%M:%S") #devUpdate = datetime.strptime(Devices[Unit].LastUpdate, "%Y-%m-%d %H:%M:%S") devUpdate = datetime(*(time.strptime(Devices[Unit].LastUpdate, "%Y-%m-%d %H:%M:%S")[0:6])) devBefore = datetime.now() - devUpdate if (devBefore > timedelta(minutes=updMinutes)): Domoticz.Debug("Updated before: " + str(devBefore) + " ("+Devices[Unit].Name+")") Devices[Unit].Update(nValue, str(sValue)) return # Generic helper functions
def timeline(request, from_date, to_date, context_id): try: from_date_date = datetime.datetime(*time.strptime(from_date, '%Y_%m_%d')[0:5]).date() to_date_date = datetime.datetime(*time.strptime(to_date, '%Y_%m_%d')[0:5]).date() except ValueError: raise Http404 context_id = int(context_id) if context_id: context_agent = get_object_or_404(EconomicAgent, pk=context_id) timeline_date = datetime.date.today().strftime("%b %e %Y 00:00:00 GMT-0600") unassigned = Commitment.objects.unfinished().filter( from_agent=None, event_type__relationship="work").order_by("due_date") return render_to_response("valueaccounting/timeline.html", { "orderId": 0, "context_id": context_id, "useContextId": 0, "from_date": from_date, "to_date": to_date, "timeline_date": timeline_date, "unassigned": unassigned, }, context_instance=RequestContext(request))
def json_timeline(request, from_date, to_date, context_id): try: start = datetime.datetime(*time.strptime(from_date, '%Y_%m_%d')[0:5]).date() end = datetime.datetime(*time.strptime(to_date, '%Y_%m_%d')[0:5]).date() except ValueError: raise Http404 context_id = int(context_id) context_agent = None if context_id: context_agent = get_object_or_404(EconomicAgent, pk=context_id) events = {'dateTimeFormat': 'Gregorian','events':[]} processes = Process.objects.unfinished().filter( Q(start_date__range=(start, end)) | Q(end_date__range=(start, end)) | Q(start_date__lt=start, end_date__gt=end)) if context_agent: processes = processes.filter(context_agent=context_agent) orders = [p.independent_demand() for p in processes if p.independent_demand()] orders = list(set(orders)) create_events(orders, processes, events) data = simplejson.dumps(events, ensure_ascii=False) #import pdb; pdb.set_trace() return HttpResponse(data, content_type="text/json-comment-filtered")
def get_time_string(status, options, format="%a %b %d %H:%M:%S +0000 %Y"): timestamp = options["timestamp"] datestamp = options["datestamp"] t = time.strptime(status['created_at'], format) i_hate_timezones = time.timezone if time.daylight: i_hate_timezones = time.altzone dt = datetime.datetime(*t[:-3]) - datetime.timedelta( seconds=i_hate_timezones) t = dt.timetuple() if timestamp and datestamp: return time.strftime("%Y-%m-%d %H:%M:%S ", t) elif timestamp: return time.strftime("%H:%M:%S ", t) elif datestamp: return time.strftime("%Y-%m-%d ", t) return ""
def __init__(self, jsondict=None): if isinstance(jsondict, dict): if jsondict is not None: self.tag = jsondict['tag'] self.security_id =jsondict['security_id'] self.data_date=time.strptime(jsondict['data_date'],"%Y-%m-%d") self.d0_wd =jsondict['d0_wd'] self.d0_open =jsondict['d0_open'] self.d1_wd = jsondict['d1_wd'] self.d1_open = jsondict['d1_open'] self.d2_wd = jsondict['d2_wd'] self.d2_open = jsondict['d2_open'] self.d3_wd = jsondict['d3_wd'] self.d3_open = jsondict['d3_open'] self.uuid=None self.announcelist = [] self.researchlist = [] self.newslist = []
def time_parse(s): try: epoch = int(s) return epoch except ValueError: pass try: epoch = int(calendar.timegm(time.strptime(s, '%Y-%m-%d'))) return epoch except ValueError: pass try: epoch = int(calendar.timegm(time.strptime(s, '%Y-%m-%d %H:%M:%S'))) return epoch except ValueError: pass m = re.match(r'^(?=\d)(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$', s, re.I) if m: return -1*(int(m.group(1) or 0)*604800 + \ int(m.group(2) or 0)*86400+ \ int(m.group(3) or 0)*3600+ \ int(m.group(4) or 0)*60+ \ int(m.group(5) or 0)) raise ValueError('Invalid time: "%s"' % s)
def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: try: expires = int(time.time() + int(morsel['max-age'])) except ValueError: raise TypeError('max-age: %s must be integer' % morsel['max-age']) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = calendar.timegm( time.strptime(morsel['expires'], time_template) ) return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, )
def _get_x509_days_left(x509): date_fmt = '%Y%m%d%H%M%SZ' current_datetime = datetime.datetime.utcnow() not_after = time.strptime(x509.get_notAfter(), date_fmt) not_before = time.strptime(x509.get_notBefore(), date_fmt) ret = {'not_after': (datetime.datetime(*not_after[:6]) - current_datetime).days, 'not_before': (datetime.datetime(*not_before[:6]) - current_datetime).days} return ret
def scroll(query, begin, until, prefix=None): diff = timedelta(minutes=4) while begin < until: to = min(begin + diff, until) res = DB.query(query % (pad(begin), pad(to))) for batch in res: for row in batch: # truncate longer ids to match with shorter host names if "container_id" in row: row["container_id"] = row["container_id"][0:11] time_col = row["time"][0:min(26, len(row["time"]) - 1)] if len(time_col) == 19: t = time.strptime(time_col, "%Y-%m-%dT%H:%M:%S") else: t = time.strptime(time_col, "%Y-%m-%dT%H:%M:%S.%f") if prefix is not None: for key in row.iterkeys(): if (key not in SKIP_PREFIX) and ((prefix + "|") not in key): row[APP_METRIC_DELIMITER.join((prefix, key))] = row.pop(key) yield (time.mktime(t), row) begin = to
def uptime(args): with os.popen("docker inspect -f '{{json .State}}' " + args.container + " 2>&1") as pipe: status = pipe.read().strip() if "No such image or container" in status: print "0" else: statusjs = json.loads(status) if statusjs["Running"]: uptime = statusjs["StartedAt"] start = time.strptime(uptime[:19], "%Y-%m-%dT%H:%M:%S") print int(time.time() - time.mktime(start)) else: print "0" # get the approximate disk usage # alt docker inspect -s -f {{.SizeRootFs}} 49219085bdaa # alt docker exec " + args.container + " du -s -b / 2> /dev/null
def test_startofyear(self): sdds_soy = Time.startOfYear() # calculate start of year soy = datetime.datetime(*(time.strptime(self.cur_year_str+"-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")[0:6])) soy_time=calendar.timegm(soy.timetuple()) self.assertEqual( sdds_soy, soy_time ) sdds_time = Time() sdds_time.setFromTime(soy_time) # calculate start of year self.assertEqual( sdds_time.gmtime(), time.gmtime(soy_time) )
def timetuple(self): return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
def _datetime_type(data): t = time.strptime(data, "%Y%m%dT%H:%M:%S") return datetime.datetime(*tuple(t)[:6]) ## # Wrapper for binary data. This can be used to transport any kind # of binary data over XML-RPC, using BASE64 encoding. # # @param data An 8-bit string containing arbitrary data.
def iso_2_utc(iso_ts): if not iso_ts or iso_ts is None: return 0 delim = -1 if not iso_ts.endswith('Z'): delim = iso_ts.rfind('+') if delim == -1: delim = iso_ts.rfind('-') if delim > -1: ts = iso_ts[:delim] sign = iso_ts[delim] tz = iso_ts[delim + 1:] else: ts = iso_ts tz = None if ts.find('.') > -1: ts = ts[:ts.find('.')] try: d = datetime.datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S') except TypeError: d = datetime.datetime(*(time.strptime(ts, '%Y-%m-%dT%H:%M:%S')[0:6])) dif = datetime.timedelta() if tz: hours, minutes = tz.split(':') hours = int(hours) minutes = int(minutes) if sign == '-': hours = -hours minutes = -minutes dif = datetime.timedelta(minutes=minutes, hours=hours) utc_dt = d - dif epoch = datetime.datetime.utcfromtimestamp(0) delta = utc_dt - epoch try: seconds = delta.total_seconds() # works only on 2.7 except: seconds = delta.seconds + delta.days * 24 * 3600 # close enough return seconds
def timestampFromString(value): return calendar.timegm(time.strptime(value)) - epoch_diff
def QA_util_date_stamp(date): datestr = str(date)[0:10] date = time.mktime(time.strptime(datestr, '%Y-%m-%d')) return date
def QA_util_time_stamp(time_): ''' ???????%Y-%m-%d %H:%M:%S ?????? ''' if len(str(time_)) == 10: # yyyy-mm-dd?? return time.mktime(time.strptime(time_, '%Y-%m-%d')) elif len(str(time_)) == 16: # yyyy-mm-dd hh:mm?? return time.mktime(time.strptime(time_, '%Y-%m-%d %H:%M')) else: timestr = str(time_)[0:19] return time.mktime(time.strptime(timestr, '%Y-%m-%d %H:%M:%S'))
def QA_util_date_valid(date): try: time.strptime(date, "%Y-%m-%d") return True except: return False
def _from_timestring(self, s): try: parts = s.split('.') base_time = time.strptime(parts[0], "%H:%M:%S") self.nanosecond_time = (base_time.tm_hour * Time.HOUR + base_time.tm_min * Time.MINUTE + base_time.tm_sec * Time.SECOND) if len(parts) > 1: # right pad to 9 digits nano_time_str = parts[1] + "0" * (9 - len(parts[1])) self.nanosecond_time += int(nano_time_str) except ValueError: raise ValueError("can't interpret %r as a time" % (s,))
def _from_datestring(self, s): if s[0] == '+': s = s[1:] dt = datetime.datetime.strptime(s, self.date_format) self._from_timetuple(dt.timetuple())
def interpret_datestring(val): if val[-5] in ('+', '-'): offset = (int(val[-4:-2]) * 3600 + int(val[-2:]) * 60) * int(val[-5] + '1') val = val[:-5] else: offset = -time.timezone for tformat in cql_timestamp_formats: try: tval = time.strptime(val, tformat) except ValueError: continue # scale seconds to millis for the raw value return (calendar.timegm(tval) + offset) * 1e3 else: raise ValueError("can't interpret %r as a date" % (val,))