Esempio n. 1
0
    def form_valid(self, form):
        bookinginfo_list = self.model.objects.all()
        date_format = '%Y-%m-%d %H:%M'

        new_start_time = str(self.request.POST['start_time'])
        new_start_day = new_start_time[:10]
        new_start_epoch = int(time.mktime(time.strptime(str(new_start_time), date_format)))

        new_end_time = str(self.request.POST['end_time'])
        new_end_epoch = int(time.mktime(time.strptime(str(new_end_time), date_format)))

        new_room_id = self.request.POST['room_id']

        for BookingInfo in bookinginfo_list:
            if str(BookingInfo.start_time + timedelta(hours=9))[:10] == new_start_day and BookingInfo.room_id == new_room_id:

                if int(time.mktime((BookingInfo.end_time + timedelta(hours=9)).timetuple())) > new_start_epoch and new_start_epoch >= int(
                        time.mktime((BookingInfo.start_time + timedelta(hours=9)).timetuple())):
                    return HttpResponseRedirect('/booking/fail')

                elif new_end_epoch > int(time.mktime((BookingInfo.start_time + timedelta(hours=9)).timetuple())) and int(
                        time.mktime((BookingInfo.start_time + timedelta(hours=9)).timetuple())) >= new_start_epoch:
                    return HttpResponseRedirect('/booking/fail')

                else:
                    pass


        form.instance.owner = self.request.user
        return super(BookingCreateView, self).form_valid(form)
Esempio n. 2
0
def insert_into_database(name, date, meal, start_time, end_time, address, event_name = None, lat = None, lng = None):
    try:
        #sanity check for the date formate
        a = datetime.strptime(date, '%Y-%m-%d')

	s_time = time.strptime(start_time, "%H:%M:%S")
	e_time = time.strptime(end_time, "%H:%M:%S")
	if e_time < s_time:
	    raise Exception("start_time is later than end_time")
        sql_args = get_sql_args(name, date, meal, start_time, end_time, address.replace("+", " "), lat, lng)
        c.execute(sql_fmt, sql_args)
        if event_name == None:
            event_name = "NULL"
        print "~~~~added one event: %s~~~~~~~" % event_name
        print sql_args
        return True
    except Exception, e: 
        print_error("sql fail (maybe)")
        print "e: %s" %  e
        print name
        print "date:%s" %date
        print "start_time: %s" % start_time
        print "end_time: %s" %end_time
        print "address: %s" %address
        print "meal: %s" %meal
        if e[0] == 1062:
            print "good error!"
            return True
        return False
Esempio n. 3
0
 def check_date(self, starttime, endtime):
     # Check that timestamps are valid and
     # that starttime < endtime
     try:
         time.strptime(starttime, "%Y-%m-%dT%H:%M:%S")
         time.strptime(endtime, "%Y-%m-%dT%H:%M:%S")
     except ValueError as error:
         print(error)
         return False
     else:
         # convert timestamps to seconds
         start = datetime.strptime(starttime, "%Y-%m-%dT%H:%M:%S")
         end = datetime.strptime(endtime, "%Y-%m-%dT%H:%M:%S")
         start = time.mktime(start.timetuple())
         end = time.mktime(end.timetuple())
         if (end - start > 168 * 60 * 6):
             self.debug("Time interval is more than 168 hours")
             self.debug("Adjust endtime to starttime + 12 hours")
             start = datetime.strptime(starttime, "%Y-%m-%dT%H:%M:%S")
             end = start + timedelta(hours=12)
             endtime = end.strftime('%Y-%m-%dT%H:%M:%S')
             starttime = start.strftime('%Y-%m-%dT%H:%M:%S')
             self.debug("starttime: " + starttime)
             self.debug("endtime: " + endtime)
             return starttime, endtime
         elif (end - start < 0):
             self.debug("endtime < startime")
             starttime, endtime = self.adjust_date(starttime, endtime)
             self.debug(
                 "Starttime is greater than endtime -> adjust startime")
             self.debug("Starttime: " + starttime)
             self.debug("Endtime: " + endtime)
             return starttime, endtime
         else:
             return starttime, endtime
Esempio n. 4
0
 def _check_transport_doc_date(self):
     # pdb.set_trace()
     if self.doc_date and self.transport_doc_date:
         newdate1 = time.strptime(self.doc_date, "%Y-%m-%d")
         newdate2 = time.strptime(self.transport_doc_date, "%Y-%m-%d")
         if newdate1 > newdate2:
             raise Warning(
                 _('Transporter document date cannot be earlier than the Invoice Date(Document Date)...!'
                   ))
Esempio n. 5
0
	def add_new_evidence(self,context, data=None):
		try:
			print data, context
			componentid,value,flags,comment,user_date,useby_date =data.split("_")
			context = context.split("/")
			ev = client.Evidence(source=self.username, evidence_type="explicit", value=value)
			if comment != 'None': ev.comment=comment
			if flags != 'None': ev.flags = flags
			if user_date != 'None': ev.time=time.mktime(time.strptime(user_date, '%d/%m/%Y'))
			if useby_date != 'None': ev.useby=time.mktime(time.strptime(useby_date, '%d/%m/%Y'))
			self.um.tell(context=context, componentid=componentid, evidence=ev)
			return True
		except Exception,e:
			return False
Esempio n. 6
0
def prepare_idTransaction_dict(model_instance):
    fields = SortedDict()
    
    for field in model_instance._meta.fields:
        try:
            if getattr(model_instance, field.name) not in (None, ''):
                newfieldname ="%s" % (field.name)
                   
                value = getattr(model_instance, field.name)
                #if a datetime sting, then turn into a datetime
                try:
                    value = time.strptime(value, "%Y-%m-%d %H:%M:%S")
                except:
                    pass
                try:
                    value = time.strptime(value, "%Y-%m-%d")
                except:
                    pass
                try:
                    value = time.strptime(value, "%H:%M:%S")
                except:
                    pass
                
            fields[newfieldname] = str(value)
        except:
            pass
    
    fields.insert(0,'_id', model_instance.transaction_id)
    if fields.has_key('extra_fields'):
        ef =json.loads(fields['extra_fields'])
        fields.update(ef)
        del fields['extra_fields']
 
    if fields.has_key('tags'):
        fields['tags'] = json.loads(fields['tags'])

    
    #print "The tx type is ", fields['transaction_type']
    if fields['transaction_type']=="omhe":
        if fields['text'] != "":
            p = parseomhe()
            d = p.parse(fields['text'])
            del d['transaction_id'], d['transaction_datetime']
            fields.update(d)
            

    #for k in fields.keys():
    #    print k,"= ",fields[k]
    
    return fields
Esempio n. 7
0
 def _check_transport_doc_date_len(self):
     # if not self.transport_doc_date:
     #     raise Warning(_('Please Enter Transporter Doc Date...!'))
     # print("in _check_transport_doc_date_len************")
     # # pdb.set_trace()
     if self.transport_doc_date:
         dt = datetime.now()
         dstr = dt.strftime("%Y-%m-%d")
         newdate1 = time.strptime(dstr, "%Y-%m-%d")
         newdate2 = time.strptime(self.transport_doc_date, "%Y-%m-%d")
         # pdb.set_trace()
         if newdate2 > newdate1:
             raise Warning(
                 _('Transporter Doc Date should not be more than today...!')
             )
Esempio n. 8
0
 def asValue(self, strValue, objType):
     '''
     Parses the string value into an object value depending on the provided object type.
     
     @param strValue: string
         The string representation of the object to be parsed.
     @param objType: Type
         The type of object to which the string should be parsed.
     @raise ValueError: In case the parsing was not successful.
     '''
     assert isinstance(objType, Type), 'Invalid object type %s' % objType
     if strValue is None: return None
     if objType.isOf(str):
         return strValue
     if objType.isOf(int):
         return int(strValue)
     if objType.isOf(float):
         return float(strValue)
     if objType.isOf(bool):
         return strValue.strip().lower() == 'true'
     if objType.isOf(datetime):
         return datetime.strptime(strValue, '%Y-%m-%d %H:%M:%S')
     if objType.isOf(date):
         return datetime.strptime(strValue, '%Y-%m-%d').date()
     if objType.isOf(time):
         return time.strptime(strValue, '%H:%M:%S').time()
     raise Exception('Invalid object type %s for converter' % objType)
Esempio n. 9
0
 def asValue(self, strValue, objType):
     '''
     Parses the string value into an object value depending on the provided object type.
     
     @param strValue: string
         The string representation of the object to be parsed.
     @param objType: Type
         The type of object to which the string should be parsed.
     @raise ValueError: In case the parsing was not successful.
     '''
     assert isinstance(objType, Type), 'Invalid object type %s' % objType
     if strValue is None: return None
     if objType.isOf(str):
         return strValue
     if objType.isOf(int):
         return int(strValue)
     if objType.isOf(float):
         return float(strValue)
     if objType.isOf(bool):
         return strValue.strip().lower() == 'true'
     if objType.isOf(datetime):
         return datetime.strptime(strValue, '%Y-%m-%d %H:%M:%S')
     if objType.isOf(date):
         return datetime.strptime(strValue, '%Y-%m-%d').date()
     if objType.isOf(time):
         return time.strptime(strValue, '%H:%M:%S').time()
     raise Exception('Invalid object type %s for converter' % objType)
Esempio n. 10
0
def add_date(date_str,add_count=1):
    date_list = time.strptime(date_str, "%Y-%m-%d")
    y, m, d = date_list[:3]
    delta = timedelta(days=add_count)
    date_result = datetime(y, m, d) + delta
    date_result = date_result.strftime("%Y-%m-%d")
    return date_result
Esempio n. 11
0
 def asValue(self, value, type):
     '''
     Parses the string value into an object value depending on the provided object type.
     
     @param value: string
         The string representation of the object to be parsed.
     @param type: Type
         The type of object to which the string should be parsed.
     @return: object
         The parsed value.
     @raise ValueError: In case the parsing was not successful.
     '''
     assert isinstance(type, Type), 'Invalid object type %s' % type
     if value is None: return None
     assert isinstance(value, str), 'Invalid value %s' % value
     
     if type.isOf(str): return value
     if type.isOf(int): return int(value)
     if type.isOf(float): return float(value)
     if type.isOf(bool):
         if value.strip().lower() == 'true': return True
         elif value.strip().lower() == 'false': return False
         raise ValueError('Invalid boolean value \'%s\'' % value)
     if type.isOf(datetime): return datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
     if type.isOf(date): return datetime.strptime(value, '%Y-%m-%d').date()
     if type.isOf(time): return time.strptime(value, '%H:%M:%S').time()
     raise ValueError('Invalid object type %s for converter' % type)
Esempio n. 12
0
 def _parserByWeek(self, item, offset=1):
     return (
         offset + 2,
         datetime.fromtimestamp(
             time.mktime(time.strptime("{} {} 1".format(item[offset + 0], item[offset + 1]), "%Y %W %w"))
         ).strftime("%s000"),
     )
Esempio n. 13
0
def getLastRunDate():
    try:
        conn = psycopg2.connect("dbname=(%s) port=(%s) user=(%s) host=(%s) password=(%s)" % (db_name, db_port, db_user, db_host, db_password))
        cur = conn.cursor()
    except:
        print('Database connection error. - Last Run Date Function')

    lastDateQ = cur.execute("SELECT MAX(active_date) FROM marketo.forms2010")

    lastDate = cur.fetchone()

    strDate = str(lastDate[0])

    lastDate2 = time.strptime(strDate,"%Y-%m-%d %H:%M:%S")

    lastDate3 = datetime(*lastDate2[0:6])

    newDate = lastDate3 + timedelta(seconds=1)

    newDate2 = str(newDate)

    index = newDate2.find(' ')

    newDate3 = newDate2[:index] + 'T' + newDate2[index:] + 'Z'

    newDate4 = newDate3.replace(" ","")


    return newDate4
Esempio n. 14
0
 def asValue(self, strValue, objType):
     """
     Parses the string value into an object value depending on the provided object type.
     
     @param strValue: string
         The string representation of the object to be parsed.
     @param objType: Type
         The type of object to which the string should be parsed.
     @raise ValueError: In case the parsing was not successful.
     """
     assert isinstance(objType, Type), "Invalid object type %s" % objType
     if strValue is None:
         return None
     if objType.isOf(str):
         return strValue
     if objType.isOf(int):
         return int(strValue)
     if objType.isOf(float):
         return float(strValue)
     if objType.isOf(bool):
         return strValue.strip().lower() == "true"
     if objType.isOf(datetime):
         return datetime.strptime(strValue, "%a, %d %b %Y %H:%M:%S")
     if objType.isOf(date):
         return datetime.strptime(strValue, "a, %d %b %Y").date()
     if objType.isOf(time):
         return time.strptime(strValue, "%H:%M:%S").time()
     raise AssertionError("Invalid object type %s for converter" % objType)
Esempio n. 15
0
 def add_evidence(self, context=[], component=None, value=None, comment=None, usertime=None):
     print component, value
     ev = Personis_base.Evidence(source="Personis_Access.py", evidence_type="explicit", value=value)
     ev.comment = comment
     if usertime:
         import time
         ev.time=time.mktime(time.strptime(usertime, '%Y-%m-%d %H:%M:%S'))
     self.um.tell(context=context, componentid=component, evidence=ev)
Esempio n. 16
0
def Reader():
inputfile="C:\Users\TP\Desktop\1\time.csv"
	with open(inputfile,'r',newline='') as filereader:
		for row in filereader:
			if row[2].strip()==(''):
				starttime=time.strptime(row[1],"%H:%M:S")
				endtime=row[4]
				print(endtime-starttime).seconds
def get_driver_num(**op_kwargs):
    driver_num = {}
    res = []
    conn = get_db_conn('mysql_oride_data_readonly')
    mcursor = conn.cursor()
    driver_id = -1
    results = tuple()
    driver_dic = {}
    while True:
        sql = query_driver_city_serv.format(id=driver_id)
        logging.info(sql)
        mcursor.execute(sql)
        conn.commit()
        tmp = mcursor.fetchall()
        if not tmp:
            break
        results += tmp
        driver_id = tmp[-1][0]

    mcursor.close()
    conn.close()
    for data in results:
        driver_dic[data[0]] = ",".join([str(data[1]), str(data[2])])
    redis_conn = RedisHook(redis_conn_id='pika_85').get_conn()
    ts = op_kwargs['ts']
    dt, h = ts.split('T')
    dt = dt + ' ' + h.split('+')[0]
    time_array = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
    timestamp = int(time.mktime(time_array))
    a_member = set()
    no_member = set()
    dt_start = time.strftime('%Y%m%d%H%M', time.localtime(timestamp))
    for i in range(0, 10):
        dt = time.strftime('%Y%m%d%H%M', time.localtime(timestamp + i * 60))
        a_member = a_member.union(set(redis_conn.smembers(active_a_driver % dt)))
        no_member = no_member.union(set(redis_conn.smembers(active_no_driver % dt)))
    for mem in a_member:
        tmp = driver_dic.get(int(mem), '0,0')
        if tmp not in driver_num:
            driver_num[tmp] = {"a_mem": 0, "no_mem": 0}
        driver_num[tmp]["a_mem"] += 1
    for mem in no_member:
        tmp = driver_dic.get(int(mem), '0,0')
        if tmp not in driver_num:
            driver_num[tmp] = {"a_mem": 0, "no_mem": 0}
        driver_num[tmp]["no_mem"] += 1

    for k, v in driver_num.items():
        info = k.split(",")
        res.append([int(info[0]), int(info[1]), dt_start+'00', v["a_mem"], v["no_mem"]])

    conn = get_db_conn('mysql_bi')
    mcursor = conn.cursor()
    mcursor.executemany(insert_driver_num, res)
    logging.info('insert num %s, data %s', len(res), str(res))
    conn.commit()
    mcursor.close()
    conn.close()
Esempio n. 18
0
def convertdate(date):
    try:
        date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%SZ")
    except TypeError:
        # TypeError: attribute of type 'NoneType' is not callable
        # Known Kodi/python error
        date = datetime(*(time.strptime(date, "%Y-%m-%dT%H:%M:%SZ")[0:6]))

    return date
Esempio n. 19
0
def convertdate(date):
    try:
        date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%SZ")
    except TypeError:
        # TypeError: attribute of type 'NoneType' is not callable
        # Known Kodi/python error
        date = datetime(*(time.strptime(date, "%Y-%m-%dT%H:%M:%SZ")[0:6]))

    return date
Esempio n. 20
0
 def get_time(self, values):
     for value in values:
         date_format = self.date_format
         try:
             value = time.strptime(value, date_format)
         except ValueError:
             self.raise_user_error('datetime_format_error',
                                   error_args=(self.field.name, value,
                                               date_format))
         return value
Esempio n. 21
0
def add_guest(request):
    eid = request.POST.get('eid', '')  # 关联发布会id
    realname = request.POST.get('realname', '')  # 姓名
    phone = request.POST.get('phone', '')  # 手机号
    email = request.POST.get('email', '')  # 邮箱

    if eid == '' or realname == '' or phone == '':
        return JsonResponse({'status': 10021, 'message': 'parameter error'})

    result = Event.objects.filter(id=eid)
    if not result:
        return JsonResponse({'status': 10022, 'message': 'event id null'})

    result = Event.objects.get(id=eid).status
    if not result:
        return JsonResponse({
            'status': 10023,
            'message': 'event status is not available'
        })

    event_limit = Event.objects.get(id=eid).limit  # 发布会限制人数
    guest_limit = Guest.objects.filter(event_id=eid)  # 发布会已添加的嘉宾数

    if len(guest_limit) >= event_limit:
        return JsonResponse({
            'status': 10024,
            'message': 'event number is full'
        })

    event_time = Event.objects.get(id=eid).start_time  # 发布会时间
    timeArray = time.strptime(str(event_time), "%Y-%m-%d %H:%M:%S")
    e_time = int(time.mktime(timeArray))

    now_time = str(time.time())  # 当前时间
    ntime = now_time.split(".")[0]
    n_time = int(ntime)

    if n_time >= e_time:
        return JsonResponse({'status': 10025, 'message': 'event has started'})

    try:
        Guest.objects.create(realname=realname,
                             phone=int(phone),
                             email=email,
                             sign=0,
                             event_id=int(eid))
    except IntegrityError:
        return JsonResponse({
            'status': 10026,
            'message': 'the event guest phone number repeat'
        })

    return JsonResponse({'status': 200, 'message': 'add guest success'})
Esempio n. 22
0
	def add_evidence(self, context=[], component=None, value=None, comment=None, usertime=None,flags=[]):
		print "Component type %s" % type(component)
		print "Component %s, Value %s" % (component,value)
		ev = client.Evidence(source="Personis_Access.py", evidence_type="explicit", value=value,flags=flags)
		ev.comment = comment
		if usertime:
			import time
			#if not usertime.time():
			#	ev.time=time.mktime(time.strptime(usertime, '%Y-%m-%d'))
			#else:	
			ev.time=time.mktime(time.strptime(usertime, '%Y-%m-%d %H:%M:%S'))
		self.um.tell(context=context, componentid=component, evidence=ev)
Esempio n. 23
0
    def list(self, location=None, page=1):
        locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
        houses = []

        logging.info('Getting LeBonCoin page %s', page)
        lbcUrl = "http://www.leboncoin.fr/ventes_immobilieres/offres/nord_pas_de_calais/pas_de_calais/?o=%s&ps=4&pe=8&ret=1" % (str(page))
        if location is not None:
            lbcUrl += "&location=%s" % (location)

        soup = self.fetch(lbcUrl)

        try:
            announcesLinks = soup.select('.list-lbc > a')
            logging.debug('Found %d announces on the page', len(announcesLinks))
            for announce in announcesLinks:
                house = House(announce['href'])
                itemSoup = self.fetch(house.url).select(".lbcContainer")[0]

                house.images = [url['content'] for url in itemSoup.select('.lbcImages meta')]
                logging.debug('Found %s images', len(house.images))

                if len(itemSoup.select('[itemprop="price"]')) > 0:
                    house.price = itemSoup.select('[itemprop="price"]')[0]['content']
                    logging.debug('Found price : %s', house.price)

                if len(itemSoup.select('[itemprop="name"]')) > 0:
                    house.title = itemSoup.select('[itemprop="name"]')[0].string
                    logging.debug('Found title : %s', house.title)

                if len(itemSoup.select('[itemprop="name"]')) > 0:
                    house.city = itemSoup.select('[itemprop="addressLocality"]')[0].string
                    logging.debug('Found city : %s', house.city)

                if len(itemSoup.select('[itemprop="name"]')) > 0:
                    house.zipCode = itemSoup.select('[itemprop="postalCode"]')[0].string
                    logging.debug('Found zip code : %s', house.zipCode)

                if len(itemSoup.select('[itemprop="description"]')) > 0:
                    house.description = "".join(itemSoup.select('[itemprop="description"]')[0].stripped_strings)
                    logging.debug('Found description : %s', house.description)

                if len(itemSoup.select('[itemprop="latitude"]')) > 0:
                    house.coord = [itemSoup.select('[itemprop="latitude"]')[0]['content'], itemSoup.select('[itemprop="longitude"]')[0]['content']]
                    logging.debug('Found coordinates : %s', house.coord)

                if len(itemSoup.select('.upload_by')) > 0:
                    uploadRe = re.search('Mise en ligne le (.*)\.', itemSoup.select('.upload_by')[0].text)
                    house.date = time.strptime(uploadRe.group(1).title(), u'%d %B À %H:%M'.encode('ISO-8859-15'))
                    logging.debug('Found date : %s', house.date)
                houses.append(house)
        except Exception, e:
            logging.warning(e)
Esempio n. 24
0
 def read_lines(self):
     daily_entries = {}
     for day_line in self.data.split("\n"):
         try:
             # date_str, visitors, uniq_visitors = day_line.split(",")
             day_stats = day_line.split(",")
         except Exception:
             pass
         else:
             try:
                 time.strptime(day_stats[0], "%Y-%m-%d")
             except Exception:
                 pass
             else:
                 date_str = day_stats[0]
                 visitors = day_stats[1]
                 if len(day_stats) > 2:
                     uniq_visitors = day_stats[2]
                     daily_entries[date_str] = [visitors, uniq_visitors]
                 else:
                     daily_entries[date_str] = [visitors]
     return daily_entries
Esempio n. 25
0
    def process_formdata(self, valuelist):
        if valuelist:
            date_str = u' '.join(valuelist)

            for format in self.formats:
                try:
                    timetuple = time.strptime(date_str, format)
                    self.data = time(timetuple.tm_hour, timetuple.tm_min, timetuple.tm_sec)
                    return
                except ValueError:
                    pass

            raise ValueError(gettext('Invalid time format'))
Esempio n. 26
0
def validateDateEs(date):
    #Funcion para validar una fecha en formato:
    #dd/mm/yyyy, dd/mm/yy, d/m/yy, dd/mm/yyyy hh:mm:ss, dd/mm/yy hh:mm:ss, d/m/yy h:m:s

    for format in [
            '%d/%m/%Y', '%d/%m/%y', '%d/%m/%Y %H:%M:%S', '%d/%m/%y %H:%M:%S'
    ]:
        try:
            result = time.strptime(date, format)
            return True
        except:
            pass
    return False
Esempio n. 27
0
    def get_next_date(self):

        key = datetime.datetime.now().strftime("%Y-%m-%d")
        if self.cache_storage.get(key, ''):
            print 'get from cache'
            return self.cache_storage.get(key)
        else:
            day = time.strftime('%Y-%m-%d', time.localtime(time.time()))
            day = time.strptime(day, "%Y-%m-%d")
            day = int(time.mktime(day))
            self.cache_storage[key] = (day + 86400)
            print 'get from caculator'
            return (day + 86400)
Esempio n. 28
0
def cal_summary_task(cur_day, dso_name):
    console_res = subprocess.Popen(
        "hadoop fs -ls /user/hive/warehouse/dso.db/" + dso_name +
        " | tail -n 10",
        shell=True,
        stdout=subprocess.PIPE)  # 更新最近10天的明细数据源的出数时间
    console_res_str = console_res.stdout.read()
    dir_info_list = console_res_str.split("\n")
    for dir_info in dir_info_list:
        # ['drwxr-xr-x', '-', 'analysis', 'supergroup', '0', '2021-01-10', '15:00', '/user/hive/warehouse/dso.db/mobiledictclient_android/day=2021-01-09']
        str_list = re.split("\s+", dir_info)
        if len(str_list) > 7:
            # dso明细数据源的day
            dso_day = re.findall("day=([\d-]*)", str_list[-1])[0]
            # 正常的话应该是dso_day的明天
            expect_day = (datetime.strptime(dso_day, "%Y-%m-%d") +
                          oneday).strftime("%Y-%m-%d")
            expect_time = expect_day + " " + expect_hour + ":00:00"
            expect_ts = time.mktime(
                time.strptime(expect_day + " " + expect_hour, "%Y-%m-%d %H"))
            # 明细数据源的实际完成时间
            finish_day = str_list[5]
            finish_day_time = str_list[5] + " " + str_list[6]
            finish_ts = time.mktime(
                time.strptime(finish_day_time, "%Y-%m-%d %H:%M"))
            late_mins = 0
            status = "success"
            # 考虑到有重跑数据的情况,
            # 1、如果完成时间跟dso_day的明天一致的话,判断延迟分钟数,有延迟的话计算延迟分钟,没有延迟的话,设定late_mins=0
            # 2、如果完成时间跟dso_day的明天不一致的话,认为这是重跑的任务,设定status=overwrite,late_mins=-0.001(可能会有明细数据源后天才出来,这种情况应该极少,暂时认定为重跑吧)
            if finish_day != expect_day:
                status = "overwrite"
                late_mins = -0.001
            elif finish_ts > expect_ts:
                late_mins = (finish_ts - expect_ts) / 60
            task_info_list.append((dso_name, dso_day, expect_time,
                                   finish_day_time + ":00", late_mins, status))
    return task_info_list
Esempio n. 29
0
def formOptions():
    global times
    opts = dict()
    if not times:  #empty start and end
        endDate = datetime.now()
        inDate = endDate + timedelta(days=-1)
        times["start"] = list()
        times["start"].append(inDate)
        times["end"] = list()
        times["end"].append(endDate)
    else:
        inDate = times["end"][len(times["end"]) - 1]
        endDate = datetime.now()
        times["start"].append(inDate)
        times["end"].append(endDate)

    start = time.strptime(inDate.strftime("%y%m%d%H%M%S"), "%y%m%d%H%M%S")
    end = time.strptime(endDate.strftime("%y%m%d%H%M%S"), "%y%m%d%H%M%S")
    opts["start"] = int(mktime(start))
    opts["end"] = int(mktime(end))
    opts["pagination"] = 100
    opts["page"] = 0
    return opts
Esempio n. 30
0
def user_sign(request):
    eid = request.POST.get('eid', '')  # 发布会id
    phone = request.POST.get('phone', '')  # 嘉宾手机号

    if eid == '' or phone == '':
        return JsonResponse({'status': 10021, 'message': 'parameter error'})

    result = Event.objects.filter(id=eid)
    if not result:
        return JsonResponse({'status': 10022, 'message': 'event id null'})

    result = Event.objects.get(id=eid).status
    if not result:
        return JsonResponse({
            'status': 10023,
            'message': 'event status is not available'
        })

    event_time = Event.objects.get(id=eid).start_time  # 发布会时间
    timeArray = time.strptime(str(event_time), "%Y-%m-%d %H:%M:%S")
    e_time = int(time.mktime(timeArray))

    now_time = str(time.time())  # 当前时间
    ntime = now_time.split(".")[0]
    n_time = int(ntime)

    if n_time >= e_time:
        return JsonResponse({'status': 10024, 'message': 'event has started'})

    result = Guest.objects.filter(phone=phone)
    if not result:
        return JsonResponse({'status': 10025, 'message': 'user phone null'})

    result = Guest.objects.filter(phone=phone, event_id=eid)
    if not result:
        return JsonResponse({
            'status':
            10026,
            'message':
            'user did not participate in the conference'
        })

    result = Guest.objects.get(event_id=eid, phone=phone).sign
    if result:
        return JsonResponse({'status': 10027, 'message': 'user has sign in'})
    else:
        Guest.objects.filter(phone=phone).update(sign='1')
        return JsonResponse({'status': 200, 'message': 'sign success'})
Esempio n. 31
0
    def create(self, vals):
        # print type(str(vals['currentdate']))

        if vals.has_key('expensedetail'):
            full_name = self.env['hr.employee'].search([
                ('login', '=', self.env.user.login)
            ]).full_name
            if not full_name:
                raise Warning(u'请先在员工档案中维护当前用户的员工信息。')
            recordname = full_name + '-' + \
                         self.env['dtdream.expense.detail'].search([('id', '=', vals['expensedetail'])])[
                             0].name + '(' + time.strftime('%Y%m%d',
                                                           time.strptime(vals['currentdate'], '%Y-%m-%d')) + ')'
            vals['name'] = recordname
        result = super(dtdream_expense_record, self).create(vals)
        return result
Esempio n. 32
0
    def value_from_datadict(self, data, files, name):
        dtf = forms.fields.DEFAULT_DATETIME_INPUT_FORMATS
        empty_values = forms.fields.EMPTY_VALUES

        value = data.get(name, None)
        if value in empty_values:
            return None
        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            return datetime.datetime(value.year, value.month, value.day)
        for format in dtf:
            try:
                return datetime.datetime(*time.strptime(value, format)[:6])
            except ValueError:
                continue
        return None
Esempio n. 33
0
    def value_from_datadict(self, data, files, name):
        dtf = forms.fields.DEFAULT_DATETIME_INPUT_FORMATS
        empty_values = forms.fields.EMPTY_VALUES

        value = data.get(name, None)
        if value in empty_values:
            return None
        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            return datetime.datetime(value.year, value.month, value.day)
        for format in dtf:
            try:
                return datetime.datetime(*time.strptime(value, format)[:6])
            except ValueError:
                continue
        return None
Esempio n. 34
0
 def decode_obj(obj):
     if b'__datetime__' in obj:
         # FIXME: not tested
         try:
             obj = datetime.strptime(obj['as_str'], DATETIME_FORMAT_NO_MS)
         except ValueError:
             # The preferred format is without the microseconds, but there are some lingering
             # bundle that still have it.
             obj = datetime.strptime(obj['as_str'], DATETIME_FORMAT_WITH_MS)
     elif b'__time__' in obj:
         # FIXME: not tested
         obj = time(*list(time.strptime(obj['as_str'], TIME_FORMAT))[3:6])
     elif b'__date__' in obj:
         # FIXME: not tested
         obj = datetime.strptime(obj['as_str'], DATE_FORMAT).date()
     else:
         # FIXME: not tested
         raise Exception('Unknown type on decode: {} '.format(obj))
     return obj
Esempio n. 35
0
 def decode_obj(obj):
     if b'__datetime__' in obj:
         # FIXME: not tested
         try:
             obj = datetime.strptime(obj['as_str'], DATETIME_FORMAT_NO_MS)
         except ValueError:
             # The preferred format is without the microseconds, but there are some lingering
             # bundle that still have it.
             obj = datetime.strptime(obj['as_str'], DATETIME_FORMAT_WITH_MS)
     elif b'__time__' in obj:
         # FIXME: not tested
         obj = time(*list(time.strptime(obj['as_str'], TIME_FORMAT))[3:6])
     elif b'__date__' in obj:
         # FIXME: not tested
         obj = datetime.strptime(obj['as_str'], DATE_FORMAT).date()
     else:
         # FIXME: not tested
         raise Exception('Unknown type on decode: {} '.format(obj))
     return obj
Esempio n. 36
0
def parse_time(ctx, time_str: str):
    time = None
    try:
        time = time.strptime(time_str, '%r')
        return time
    except:
        try:
            time = time.strptime(time_str, '%R')
            return time
        except:
            pass
    if time_str[-2:].upper() in ('AM', 'PM', 'A', 'P'):
        try:
            time = time.strptime(time_str, '%I:%M%P')
        except:
            try:
                time = time.strptime(time_str, '%I:%M %P')
            except:
                try:
                    time = time.strptime(time_str, '%I.%M%P')
                except:
                    try:
                        time = time.strptime(time_str, '%I.%M %P')
                    except:
                        ctx.send(
                            'Couldn\'t parse time string. Use `.` or `:` to seperate hour and minute. You can either use 12 or 24 hour format.'
                        )
                        return None
    else:
        try:
            time = time.strptime(time_str, '%H:%M')
        except:
            try:
                time = time.strptime(time_str, '%H:%M')
            except:
                ctx.send(
                    'Couldn\'t parse time string. Use `.` or `:` to seperate hour and minute. You can either use 12 or 24 hour format.'
                )
                return None
    return time
Esempio n. 37
0
    def _object_decode(self, obj):
        type = obj.get('__type__', None)

        typemap = {
            'datetime':
            lambda x: datetime.strptime(x['__repr__'], "%Y-%m-%dT%H:%M:%S.%fZ"
                                        ),
            'date':
            lambda x: date.strptime(x['__repr__'], "%Y-%m-%d"),
            'time':
            lambda x: time.strptime(x['__repr__'], "%H:%M:%S.%fZ"),
            'timedelta':
            lambda x: timedelta(seconds=x['__repr__']),
            'decimal':
            lambda x: Decimal(x['__repr__']),
            None:
            lambda x: x
        }

        return typemap[type](obj)
Esempio n. 38
0
def getData(csv_input):
        data=""
        reader=csv.DictReader( csv_input.split( os.linesep ) )
        for record in reader:
		data+="""

    <item>
      <title>%s</title>
      <description>%s</description>
      <guid>%s</guid>
      <link>%s</link>
      <pubDate>%s</pubDate>
    </item>
		"""%(record['title'],cgi.escape(record['description']),record['guid'],record['link'],strftime("%a, %d %b %Y %H:%M:%S +0000",time.strptime(record['pubDate'],"%Y-%m-%d %H:%M:%S")))
	return data
Esempio n. 39
0
def dateStringToDateObject(self, dateString):#Takes MM/DD/YYYY and turns into a standard dateTime object
#dateString = "16/6/1981"
    date_object = time.strptime(dateString, "%d/%m/%Y")
    return date_object
	def show_current_goal(self,fbt,form):
		import datetime
		today = datetime.datetime.now()
		current_date = date(today.year, today.month, today.day)
		#keys = ('year','month','day','steps','intense','moderate','light','sedentary')
		if form == "steps":
			keys = ('year','month','day','steps')
		elif form == "calories":
			keys = ('year','month','day','calories')
		else:
			keys = ('activity_level','active_mins')
		
		context = ['Goals','Health','CurrentLevelGoal']
		
		feedback_freq = self.personis_um.get_evidence_new(context=context, componentid="feedback_freq")
		print "feedback %s" % feedback_freq[-1].value #-- Take latest goal feedback type
		
		app_plugin = self.personis_um.get_evidence_new(context=context, componentid="app_plugin")

		start_time = time.localtime(int(feedback_freq[-1].creation_time))
		set_date = date(start_time[0], start_time[1], start_time[2])

		goal_duration = self.personis_um.get_evidence_new(context=context, componentid="goal_duration")
		#-- Take latest goal span
		betweendays = self.get_days_in_between(goal_duration[-1].value)
		end_date = set_date + timedelta(days = betweendays)
		
		interval = 0
		prev_date = ""
		# You have reached  the end 
		if current_date >= end_date: 
		   return json.dumps([{"goalEnd" : "Goal duration ends"}])		   
		   
	    #-------------------------Temporary fake setup------------------------
		email_id = self.personis_um.get_evidence_new(context = ['Personal'], componentid="email")
		emails = str(email_id[-1].value)
		print "Is fake alex?",emails.find("personis")
		
			
		#---This is just to check on what date you are start viewing the goal chart 
		start_graph_date = self.personis_um.get_evidence_new(context = context, componentid='graph_startdate')
		print "Date ",start_graph_date[-1].value, "with flag ",start_graph_date[-1].flags[0]
		startgraph_date = time.strptime(start_graph_date[-1].value, "%d/%m/%Y")   
		startgraph_date = date(startgraph_date[0], startgraph_date[1], startgraph_date[2])
		goal_list = []
		if start_graph_date[-1].flags[0] == "Revised":
			if current_date != startgraph_date:			
				startgraph_date_old = time.strptime(start_graph_date[-2].value, "%d/%m/%Y")   
				startgraph_date_old = date(startgraph_date[0], startgraph_date[1], startgraph_date[2])
				days_old = (startgraph_date - startgraph_date_old).days
				endgraph_date_old = startgraph_date_old + timedelta(days = 7)
				print "End this chart on ",endgraph_date
							
				if startgraph_date <= endgraph_date_old:
					#for i in range(0,days_old-1):
					#   goal_list[i] = "old"   
					#for j in range(days_old,6):
					#   goal_list[j] = "new"
					prev_date = startgraph_date_old
				else:					
					prev_date = startgraph_date_old
			else:			
				self.personis_um.add_evidence(context=context, component='graph_startdate', value=start_graph_date[-1].value, flags=['Updated'])
				prev_date = startgraph_date
				#for j in range(0,6):
				#	goal_list[j] = "new"
					
		else:
			if emails.find("personis") == -1:
				endgraph_date = startgraph_date + timedelta(days = 6)
				print "End this chart on ",endgraph_date
				
				if current_date >= endgraph_date:  
					start_goal_weekday = self.personis_um.get_evidence_new(context = context, componentid='goal_startday')
					print "start on day ",start_goal_weekday[-1].value
					dayofweek = start_goal_weekday[-1].value
					pass_date = current_date
					day_of_week = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]				
					print "Weekday:", current_date.weekday()
					while dayofweek != day_of_week[pass_date.weekday()]:
						  pass_date = pass_date + timedelta(days = 1)  
					start_graph = pass_date.strftime("%d/%m/%Y")
					startgraph_date = pass_date
					print "Showing graph window from ",start_graph
					self.personis_um.add_evidence(context=context, component='graph_startdate', value=start_graph, flags=['Updated'])
					   
					prev_date = startgraph_date
					#for j in range(0,6):
					#	goal_list[j] = "new"
				else:
				    prev_date = startgraph_date
			else:
				prev_date = startgraph_date	
				
		past_next  = "next"   
		print "goal set on %s %d days ago" % (prev_date, interval)
		print "pursue goal for %s for %d days" % (end_date,betweendays) 
		interval = 7
		if form != 'active_mins':
		   json_data = fbt.resolver_fitbit(self.personis_um, form, prev_date, interval, past_next, keys)
		else:
		   json_data = fbt.resolver_fitbit_active_mins(self.personis_um, prev_date, set_date, interval, past_next, keys=keys)
		print json_data
		return json_data
		"""			 
Esempio n. 41
0
# It's Monday, January 01, 1900, local time: 12:03:00PM

# Another way to write it:
import datetime

time_str = datetime.datetime.now().strftime('%m-%d-%Y, %H:%M %p')
print(time_str)  # 12-31-2017, 10:47 AM

# To go the other way and convert a string to a date or time, use strptime()
# the nonformat parts of the string (without %) need to match EXACTLY.
# Example: specify a format that matches year-month-day, such as 2017-08-16.

import time

fmt = '%Y-%m-%d'
a_date = time.strptime('2017-08-16', fmt)

print(a_date)
# time.struct_time(tm_year=2017, tm_mon=8, tm_mday=16, tm_hour=0, tm_min=0,
# tm_sec=0, tm_wday=2, tm_yday=228, tm_isdst=-1)

# NOTE: strptime is actually super useful when working with databases.
# For example, if you create a DateTime type column in an sqlite3 database,
# it will require a datetime object but depending on how you retrieve the
# data, my return a date string. Using strptime, you can convert these
# strimgs back again:

n = datetime.now()  # 2019-07-08 09:57:26.976697 <class 'datetime.datetime'>
s = str(n)
f = '%Y-%m-%d %H:%M:%S.%f'
d = datetime.strptime(s, f)
	def show_goal_with_target(self,fbt,form, goal_type, past_next, st_date):
		
		import datetime
		today = datetime.datetime.now()
		current_date = date(today.year, today.month, today.day)
		keys = ('year','month','day','steps','prev_remain','remain','prev_target','cur_target','notes')
		if form == "steps":
			keys = ('year','month','day','steps','prev_remain','remain','prev_target','cur_target','notes')
		elif form == "calories":
			keys = ('year','month','day','calories','prev_remain','remain','prev_target','cur_target','notes')
		else:
			keys = ('year','month','day','active_mins','prev_remain','remain','prev_target','cur_target','notes')
			
		#-- Look for the goal type	
		context = ['Goals','Health']
		context.append(goal_type)
		
		#-- Take current goal target
		goal_target_val = self.personis_um.get_evidence_new(context = context, componentid="target_value")
		print "target %s" % goal_target_val[-1].value 
		goal_target = (goal_target_val[-1].value).split(' ')[0]
		
		#-- Take previous goal target		
		
		goal_target_prev = "0" 
		if len(goal_target_val) > 1:			
		   for tval in goal_target_val[::-1]:
			   if tval.flags[0] == "New" or tval.flags[0] == "Used":
				  goal_target_prev = (tval.value).split(' ')[0] 
				  print "Previous target %s" % tval.value

		
		#-- Take latest goal goal target
		goal_target_freq = self.personis_um.get_evidence_new(context = context, componentid="target_frequency")
		print "do every %s" % goal_target_freq[-1].value 
		
		#-- Take latest goal feedback type
		feedback_freq = self.personis_um.get_evidence_new(context = context, componentid="feedback_freq")
		print "feedback %s" % feedback_freq[-1].value 
		
		#-- See what is the plugin for this goal...For now it is not checked....
		app_plugin = self.personis_um.get_evidence_new(context=context, componentid="app_plugin")
		
		#--When the goal started
		goal_startdate = self.personis_um.get_evidence_new(context=context, componentid="goal_startdate")		
		start_time = time.localtime(int(goal_startdate[-1].creation_time))
		st_date = date(start_time[0], start_time[1], start_time[2])

		#-- Take latest goal duration..how long you will pursue the goal
		goal_duration = self.personis_um.get_evidence_new(context=context, componentid='goal_duration')

		#--How many days in between the goal set date and goal finish deadline
		betweendays = self.get_days_in_between(goal_duration[-1].value)
		end_date = st_date + timedelta(days = betweendays)
		interval = 0 

		#---Check whether you have already reached the end date
		if current_date >= end_date:		   
		   return [{"goalEnd" : "Goal duration ends"}]  
	   
		
			 
		#---creating a list of all the dates within the interval
		for i in range(0,interval):
			newdate = end_date - timedelta(days=i)
			date_list.append(newdate)
			check_list.append(0)
  
		
		#---This is just to check on what date you are start viewing the goal chart 
		start_graph_date = self.personis_um.get_evidence_new(context = context, componentid='graph_startdate')
		print "Starting the graph window ", start_graph_date[-1].value
		startgraph_date = time.strptime(start_graph_date[-1].value, "%d/%m/%Y")   
		startgraph_date = date(startgraph_date[0], startgraph_date[1], startgraph_date[2])
		goal_list = list()
		goal_list_prev = list()
		
		final_date = ""
		startgraph_date_old = None
		if start_graph_date[-1].flags[0] == "Revised":
		   print "But as this date is flagged as Revised, "
		   if current_date != startgraph_date:  
	 		  for st_date in start_graph_date[::-1]:
				  if st_date.flags[0] == "New" or st_date.flags[0] == "Used":
					   print "Start the window from", st_date.value
					   startgraph_date_old = time.strptime(st_date.value, "%d/%m/%Y")   
					   startgraph_date_old = date(startgraph_date_old[0], startgraph_date_old[1], startgraph_date_old[2])
					   break
				
			  days_old = (startgraph_date - startgraph_date_old).days
			  print "The new date is ", days_old, " days away from the old date"
			  endgraph_date_old = startgraph_date_old + timedelta(days = 7)
			  print "The old chart window ends on ",endgraph_date_old
			  goal_target_prev2 = "0" 
			  if len(goal_target_val) > 2:
				   for tval in goal_target_val[::-2]:
					   if tval.flags[0] == "New" or tval.flags[0] == "Used":
						  goal_target_prev2 = (tval.value).split(' ')[0] 
						  print "Previous previous target %s" % tval.value
								
			  if startgraph_date <= endgraph_date_old:
				   print "As the new date falls within old chart window"
				   print "Current and previous targets for the days between old and new start date are", goal_target_prev, " and ",goal_target_prev2
				   for i in range(0,days_old):			 
					   goal_list.append(goal_target_prev)
					   goal_list_prev.append(goal_target_prev2)  
					   print "Current and previous targets for the days between new start and end window date are", goal_target, " and ",goal_target_prev	
				   for j in range(days_old,7):
					   goal_list.append(goal_target)
					   goal_list_prev.append(goal_target_prev)
				   	   final_date = startgraph_date_old
			  else:
					print "As the new date falls outside old chart window"
					print "Current and previous targets for the days between old start and end date are", goal_target_prev, " and ",goal_target_prev2
					for i in range(0,7):			 
					   goal_list.append(goal_target_prev)
					   goal_list_prev.append(goal_target_prev2)										  
					   final_date = startgraph_date_old
		   else:
				print "As the new date is today"
				print "Current and previous targets are", goal_target, " and ",goal_target_prev, "and update the flags as Used"
				print "A new time window will start from now on."				
				self.personis_um.add_evidence(context=context, component='graph_startdate', value=start_graph_date[-1].value, flags=['Used'])
				self.personis_um.add_evidence(context=context, component='target_value', value=goal_target_val[-1].value, flags=['Used'])
			
				final_date = startgraph_date
				for j in range(0,7):
					goal_list.append(goal_target)
					goal_list_prev.append(goal_target_prev)
		else:
			print "A new time window starts from now on as the date is not revised."				
			endgraph_date = startgraph_date + timedelta(days = 7)
			print "The chart ends on ",endgraph_date				   
			if current_date > endgraph_date:  
				   print "As today is outside the last time window, update the time window"		
				   start_goal_weekday = self.personis_um.get_evidence_new(context = context, componentid='goal_startday')
				   print "Get the weeday when the goal starts", start_goal_weekday[-1].value
				   dayofweek = start_goal_weekday[-1].value
				   pass_date = current_date
				   day_of_week = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]				
				   print "Weekday:", current_date.weekday()
				   while dayofweek != day_of_week[pass_date.weekday()]:
					  pass_date = pass_date + timedelta(days = 1)  
				   start_graph = pass_date.strftime("%d/%m/%Y")
				   startgraph_date = pass_date
				   print "New chart window start date is ",start_graph
				   self.personis_um.add_evidence(context=context, component='graph_startdate', value=start_graph, flags=['Used'])
				   print "Current and previous targets are", goal_target, " and ",goal_target_prev, "and update the flags as Used"
		   
				   final_date = startgraph_date
				   for j in range(0,7):
					   goal_list.append(goal_target)
					   goal_list_prev.append(goal_target_prev)
			else:
				   print "As today is inside the current chart window"
				   print "Current and previous targets are", goal_target, " and ",goal_target_prev, "and no update is needed"
		
				   final_date = startgraph_date
				   for j in range(0,7):
					   goal_list.append(goal_target)
					   goal_list_prev.append(goal_target_prev)
				
		#----Just a small check to set interval in default 7 days so you can see a default graph just after you've set the goal
		if past_next == "none": 
			prev_date = final_date
			interval = 7 
			past_next = "next"
		elif past_next == "past":
			prev_date = st_date
			interval = 7
			past_next = "next"
		elif past_next == "next":
			prev_date = st_date
			interval = 7
			past_next = "next"
		   
		print "goal set on %s %d days ago" % (prev_date, interval)
		print "pursue goal for %s for %d days" % (end_date,betweendays) 
		new_evdlist = list()
		daycount = 1
		
		date_list = []
		check_list = []
		
		#--- If form is steps and calories,you get to see the column chart
		#if form == "steps": 
		#json_data = fbt.resolver_fitbit_with_target(self.personis_um, context, form, prev_date, interval, past_next, keys, goal_target, goal_target_prev,)
		json_data = fbt.resolver_fitbit_with_target(self.personis_um, context, form, prev_date, interval, past_next, keys, goal_list,goal_list_prev)			
		print json_data
		return json_data
Esempio n. 43
0
def make_date(date_str):
    dt = time.strptime(date_str, '%a %b %d %H:%M:%S %Y')
    return dt
Esempio n. 44
0
date_difference = (parse(end_date, dayfirst=True) -
                   parse(start_date, dayfirst=True)).days
no_samples = (date_difference + 1) * intervals_in_day

#Initialise 2d X array for x and y
X = [[0 for x in range(len(rooms) + 10)] for y in range(no_samples)]
Y = [[0 for x in range(len(rooms) + 1)] for y in range(no_samples)]

#Set time for first array
X[0][2] = "00:00"
X[0][3] = np.sin(2 * np.pi * 0 / seconds_in_day)
X[0][4] = np.cos(2 * np.pi * 0 / seconds_in_day)

#--------------Populate X array with correct time---------------

current_time = time.strptime("00:00", "%H:%M")

for i in range(no_samples - 1):

    #Increment time by specified interval
    updated_min = current_time.tm_min + interval_mins
    updated_hour = current_time.tm_hour
    # Increment hour if needed
    if (updated_min >= 60):
        #If it is a new day reset to 00:00
        if (updated_hour >= 23):
            updated_hour = 00
            updated_min = 00
        else:
            updated_hour = current_time.tm_hour + 1
            updated_min = updated_min - 60
Esempio n. 45
0
 def __parse_date(self, date):
     return time.strptime(date, "%H:%M %p, DAY %j")
Esempio n. 46
0
闰年判断
月有几天等等
'''
import time

seconds = time.time()
print(seconds)
local_time = time.localtime()
print(local_time)
str_time = time.asctime(local_time)
print(str_time)
format_time = time.strftime('%Y-%m-%d %H:%M:%S', local_time)
print(format_time)
# time 类 strptime 方法,解析( parse) 输入的时间字符串为 struct_time 类型的时间。
# 注意:第二个参数的时间格式,要匹配上第一个参数的时间格式。
str_to_struct = time.strptime(format_time, '%Y-%m-%d %H:%M:%S')
print(str_to_struct)
'''
记住常用的时间格式:
    %Y  年
    %m  月 取值 [01,12]
    %d  天 取值 [01,31]
    %H  小时 取值 [00,23]
    %M  分钟 取值 [00,59]
    %S  秒 取值 [00,61]
'''
# datetime 模块
# 从 datetime 模块中,依次导入类:date、datetime、time、timedelta。
#from datetime import date, datetime, time, timedelta
tod = date.today()
print(tod, type(tod))
Esempio n. 47
0
    def valid(self, value):
        try:

            return value!=u"01/01/1900" and time.strptime(value, '%d/%m/%Y')
        except ValueError:
            return False
Esempio n. 48
0
	def check_goals(self):
		"""
		try:
		  contextlist = self.all_access_model(cont=["Devices"])
		except Exception,e:
		  print "Devices not found error",e
		try:
		  contextlist2 = self.all_access_model(cont=["Apps"])
		except Exception,e:
		  print "Apps not found error",e							
		contextlist = contextlist + contextlist2
		"""
		goalcontext = ['Goals','Health'] 
		goalcontext_obj = self.all_access_model(cont=goalcontext)
		print goalcontext_obj
		import datetime
		today = datetime.datetime.now()
		current_date = date(today.year, today.month, today.day)
		app_goal_list = list()
		goal_list = ["CurrentLevelGoal","StepGoal","ModerateActivityGoal","IntenseActivityGoal","AvoidInactivityGoal"]
		for g in goal_list:				   
			if g in goalcontext_obj:
			   goalcontext.append(g)
			   show_chart = 0
			   
			   #---Get the target value 
			   goal_target_val = self.get_evidence_new(context = goalcontext, componentid="target_value")
			   print goal_target_val
			   try:
				   if goal_target_val:
					 goal_target_v = (goal_target_val[-1].value).split(' ')[0]
				   else:
					 goal_target_v = "none"
			   except Exception,e:
				   print e	
			   
			   #--Find out how many times in a week you are following the goal
			   goal_target_freq = self.get_evidence_new(context = goalcontext, componentid="target_frequency")
			   if goal_target_freq:
				   goal_target_f = (goal_target_freq[-1].value).split(' ')[0]
			   else:
				   goal_target_f = "none"			   
			   
			   #--Find out when the goal was set
			   goal_startdate = self.get_evidence_new(context=goalcontext, componentid="goal_startdate")
			   
			   #--How many days in between the goal set date 
			   goal_duration = self.get_evidence_new(context=goalcontext, componentid="goal_duration")
			   if goal_duration[-1].value == "no change":
			   	  for dd in goal_duration[::-1]:
			   	  	 if dd.value != "no change":
			   	  	 	betweendays = self.get_days_in_between(dd.value)
			   	  	 	break
			   else:
			      betweendays = self.get_days_in_between(goal_duration[-1].value)

			   #---Get the date when the goal is set and how many days have been passed
			   #start_time = time.localtime(int(goal_startdate[-1].creation_time))
			   
			   start_time = time.mktime(time.strptime(goal_startdate[-1].value, '%d/%m/%Y'))
			   start_time = time.localtime(int(start_time))
			   goal_start_date = date(start_time[0], start_time[1], start_time[2])
			   print "This goal is set on ", goal_start_date
			   print "This goal will go for", goal_duration[-1].value
			   days_passed = (current_date - goal_start_date).days

			   #---Get the date when the goal will end
			   goal_end_date = goal_start_date + timedelta(days = betweendays)							  
			   
			   #--Find out whether the goal is still on. If it is still on, then show the chart and check how many days left. Beacuse there might be data from previous goal.
			   
			   days_left = 0
			   days_target_needed_to_be_met = 0 
			   days_target_met = 0
			   if goal_end_date >= current_date:
				  show_chart = 1
				  days_left =  (goal_end_date - current_date).days

			   email_id = self.get_evidence_new(context = ['Personal'], componentid="email")
			   if email_id[-1].value == "*****@*****.**" and g == "CurrentLevelGoal":
				  days_passed = 5
				  days_left = 2
				  show_chart = 1
				  days_target_needed_to_be_met = 0
				  days_target_met = 0
				  
			   if email_id[-1].value == "*****@*****.**" and g == "StepGoal":
				  days_passed = 0
				  days_left = 12 * 7
				  days_target_needed_to_be_met = 0
				  days_target_met = 0
				  
			   if email_id[-1].value == "*****@*****.**" and g == "CurrentLevelGoal":
				  days_passed = 7
				  days_left = 0
				  show_chart = 0
				  days_target_needed_to_be_met = 0
				  days_target_met = 0
				  
			   if email_id[-1].value == "*****@*****.**" and g == "StepGoal":
				  days_passed = 25
				  days_left = 9 * 7 + 3
				  show_chart = 1
				  #if goal_target_val[-1].flags[0] == "New": 	
				  days_target_needed_to_be_met = 17
				  days_target_met = 14
				  #elif goal_target_val[-1].flags[0] == "Revised": 
				  #	 days_target_needed_to_be_met = 0 
				  #	 days_target_met = 0
				  
			   if email_id[-1].value == "*****@*****.**" and g == "CurrentLevelGoal":
				  days_passed = 7
				  days_left = 0
				  show_chart = 0

			   if email_id[-1].value == "*****@*****.**" and g == "StepGoal":
				  days_passed = 11 * 7 + 2
				  days_left = 5
				  show_chart = 1
				  #if goal_target_val[-1].flags[0] == "New": 
				  days_target_needed_to_be_met = 11 * 7 + 2
				  days_target_met = 70
			   
			   print "Days:::",days_passed, days_left      
			   new_goal = goals_set(g, goal_target_v, goal_target_f, show_chart, days_passed, days_left, days_target_needed_to_be_met, days_target_met) 
			   
			   app_goal_list.append(self.todict(new_goal, new_goal.name))
			   goalcontext.remove(g)				
Esempio n. 49
0
def axivity_parse_header(fh):

    ax_header = OrderedDict()

    blockSize = unpack('H', axivity_read(fh,2))[0]
    performClear = unpack('B', axivity_read(fh,1))[0]
    deviceId = unpack('H', axivity_read(fh,2))[0]
    sessionId = unpack('I', axivity_read(fh,4))[0]
    shippingMinLightLevel = unpack('H', axivity_read(fh,2))[0]
    loggingStartTime = axivity_read(fh,4)
    loggingEndTime = axivity_read(fh,4)
    loggingCapacity = unpack('I', axivity_read(fh,4))[0]
    allowStandby = unpack('B', axivity_read(fh,1))[0]
    debuggingInfo = unpack('B', axivity_read(fh,1))[0]
    batteryMinimumToLog = unpack('H', axivity_read(fh,2))[0]
    batteryWarning = unpack('H', axivity_read(fh,2))[0]
    enableSerial = unpack('B', axivity_read(fh,1))[0]
    lastClearTime = axivity_read(fh,4)
    samplingRate = unpack('B', axivity_read(fh,1))[0]
    lastChangeTime = axivity_read(fh,4)
    firmwareVersion = unpack('B', axivity_read(fh,1))[0]

    reserved = axivity_read(fh,22)

    annotationBlock = axivity_read(fh, 448 + 512)

    if len(annotationBlock) < 448 + 512:
        annotationBlock = ""

    annotation = ""
    for x in annotationBlock:
        if x != 255 and x != ' ':
            if x == '?':
                x = '&'
            annotation += str(x)
    annotation = annotation.strip()

    annotationElements = annotation.split('&')
    annotationNames = {
        '_c': 'studyCentre',
        '_s': 'studyCode',
        '_i': 'investigator',
        '_x': 'exerciseCode',
        '_v': 'volunteerNum', '_p':
        'bodyLocation', '_so':
        'setupOperator', '_n': 'notes',
        '_b': 'startTime', '_e': 'endTime',
        '_ro': 'recoveryOperator',
        '_r': 'retrievalTime',
        '_co': 'comments'
    }

    for element in annotationElements:
        kv = element.split('=', 2)
        if kv[0] in annotationNames:
            ax_header[annotationNames[kv[0]]] = kv[1]

    for x in ('startTime', 'endTime', 'retrievalTime'):
        if x in ax_header:
            if '/' in ax_header[x]:
                ax_header[x] = time.strptime(ax_header[x], '%d/%m/%Y')
            else:
                ax_header[x] = time.strptime(ax_header[x], '%Y-%m-%d %H:%M:%S')


    lastClearTime = axivity_read_timestamp(lastClearTime)
    lastChangeTime = axivity_read_timestamp(lastChangeTime)
    firmwareVersion = firmwareVersion if firmwareVersion != 255 else 0


    #ax_header["sample_rate"] = samplingRate
    ax_header["device"] = deviceId
    ax_header["session"] = sessionId
    ax_header["firmware"] = firmwareVersion
    #ax_header["logging_start_time"] = axivity_read_timestamp_raw(loggingStartTime)
    #ax_header["logging_end_time"] = axivity_read_timestamp_raw(loggingEndTime)


    ax_header["frequency"] = 3200/(1<<(15-(int(samplingRate) & 0x0f)))


    return ax_header
Esempio n. 50
0
		# wait for button release
		start_button_up = GPIO.input(18)
		while start_button_up == False:
			blink(.1)
			start_button_up = GPIO.input(18)			
		
		started = True
		firstrun = True
	try:
		os.system('clear')
		report = gpsp.get_current_value()
		if report.keys()[0] == 'epx':
			GPIO.output(4,True)
			lasttime = report.time
			if firstrun == True:
				gpstime = time.strptime(report.time, "%Y-%m-%dT%H:%M:%S.%fZ")
				timestr = time.strftime("%Y-%m-%d-%H.%M.%S", gpstime)
				writemdfile(report.lat, report.lon, timestr)
				cachefilepath = repopath + "sailtrack/" + timestr + ".csv"
				cachefile = open(cachefilepath, 'w', 1)
				firstrun = False
				
			cachefile.write(str(round(report['lon'], 5)) + ",")
			cachefile.write(str(round(report['lat'], 5)) + ",")
			cachefile.write(str(report['time']) + ",")
			cachefile.write(str(report['speed']) + "\n")
			start_button_up = GPIO.input(18)
			pausecount = 1
			
			while start_button_up == True and pausecount < captureinterval:
				time.sleep(1)
Esempio n. 51
0
>>> t = time.localtime()
>>> t
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=16, tm_hour=14, tm_min=16, tm_sec=0, tm_wday=1, tm_yday=16, tm_isdst=0)
>>> time.strftime(fmt, t)
"It's Tuesday, January 16, 2018, local time 02:16:00PM"
>>> from datetime import date
>>> some_day = date(2014, 7, 4)
>>> some_day.strftime(fmt)
"It's Friday, July 04, 2014, local time 12:00:00AM"
>>> from datetime import time
>>> some_time = time(10, 35)
>>> some_time.strftime(fmt)
"It's Monday, January 01, 1900, local time 10:35:00AM"
>>> import time
>>> fmt = "%Y-%m-%d"
>>> time.strptime("2012 01 29", fmt)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 494, in _strptime_time
    tt = _strptime(data_string, format)[0]
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2012 01 29' does not match format '%Y-%m-%d'
>>> time.strptime("2012-01-29", fmt)
time.struct_time(tm_year=2012, tm_mon=1, tm_mday=29, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=29, tm_isdst=-1)
>>> time.strptime("2012-13-29", fmt)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 494, in _strptime_time
    tt = _strptime(data_string, format)[0]
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 337, in _strptime
Esempio n. 52
0
def toDate(datestr):
    return time.strptime(datestr,"%Y-%m-%d")
	def onchange_employee_id(self, cr, uid, ids, date_from, date_to, employee_id=False, contract_id=False, context=None):
		empolyee_obj = self.pool.get('hr.employee')
		contract_obj = self.pool.get('hr.contract')
		worked_days_obj = self.pool.get('hr.payslip.worked_days')
		input_obj = self.pool.get('hr.payslip.input')

		if context is None:
			context = {}
		#delete old worked days lines
		old_worked_days_ids = ids and worked_days_obj.search(cr, uid, [('payslip_id', '=', ids[0])], context=context) or False
		if old_worked_days_ids:
			worked_days_obj.unlink(cr, uid, old_worked_days_ids, context=context)

		#delete old input lines
		old_input_ids = ids and input_obj.search(cr, uid, [('payslip_id', '=', ids[0])], context=context) or False
		if old_input_ids:
			input_obj.unlink(cr, uid, old_input_ids, context=context)


		#defaults
		res = {'value':{
					'line_ids':[],
					'input_line_ids': [],
					'worked_days_line_ids': [],
					#'details_by_salary_head':[], TODO put me back
					'name':'',
					'contract_id': False,
					'struct_id': False,
					'contract_structure':None
					}
			}
		if (not employee_id) or (not date_from) or (not date_to):
			return res
		ttyme = datetime.fromtimestamp(time.mktime(time.strptime(date_from, "%Y-%m-%d")))
		employee_id = empolyee_obj.browse(cr, uid, employee_id, context=context)
		res['value'].update({
				'name': _('Salary Slip of %s for %s') % (employee_id.name, tools.ustr(ttyme.strftime('%B-%Y'))),
				'company_id': employee_id.company_id.id,
				'employee_name':employee_id.name_related,		# Customize
				'contract_id':employee_id.cont_id.id,
				'struct_id':employee_id.structure_id.id,
				'contract_structure':str(employee_id.cont_id.type_id.name)  + '/' + str(employee_id.cont_id.contract_type.name) + '/' +  							str(employee_id.cont_id.contract_detail.name)
						})
		'''
		if not context.get('contract', False):
		#fill with the first contract of the employee
			contract_ids = self.get_contract(cr, uid, employee_id, date_from, date_to, context=context)
		else:
			if contract_id:
			#set the list of contract for which the input have to be filled
				contract_ids = [contract_id]
			else:
			#if we don't give the contract, then the input to fill should be for all current contracts of the employee
				contract_ids = self.get_contract(cr, uid, employee_id, date_from, date_to, context=context)

		if not contract_ids:
			return res
		contract_record = contract_obj.browse(cr, uid, contract_ids[0], context=context)
		res['value'].update({
					'contract_id': employee_id.cont_id.id#contract_record and contract_record.id or False
		})
		struct_record = contract_record and contract_record.struct_id or False
		if not struct_record:
			return res
		res['value'].update({
					'struct_id': struct_record.id,
		})
		#computation of the salary input
		worked_days_line_ids = self.get_worked_day_lines(cr, uid, contract_ids, date_from, date_to, context=context)
		input_line_ids = self.get_inputs(cr, uid, contract_ids, date_from, date_to, context=context)
		res['value'].update({
				'worked_days_line_ids': worked_days_line_ids,
				'input_line_ids': input_line_ids,
		})
		'''
		return res
Esempio n. 54
0
def get_time(a_string):
    for seTime in StandardEventTimes:
        if a_string == seTime[0]:
            return seTime[1]
    return (time.strptime(a_string, "%H:%M")).time()
Esempio n. 55
0
 def time_from_str(hora, fmt='%H:%M:%S'):
     try:
         tm = time.strptime(hora, fmt)
     except ValueError:
         tm = time.strptime(hora, fmt[:-3])
     return datetime.time(tm.tm_hour, tm.tm_min, tm.tm_sec)