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()
python类strptime()的实例源码
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 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 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 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 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 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 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,
)