def main(): date_str = "2021-06-03 16:46:00" du = DateUtils() result = du.str_to_date(date_str) print(result, type(result)) # out: 2021-06-03 16:46:00 <class 'datetime.datetime'>
def __get_endpoint(self, last_update_date, pos): """Returns the end-point to call given a date (`/{pos}/recent` or `/{pos}/last`). Arguments: last_update_date -- the date of the last update the user has saved locally; pos -- flag to choose between Bot IPs POS feed and the normal one. """ logger = logging.getLogger('__get_endpoint') pos_prefix = 'pos_' if pos else '' now = DateUtils.now() now_str = DateUtils.to_iso_date(now) if last_update_date is None: logger.info(self.__MESSAGES['no_last_update']) return self.__END_POINTS[pos_prefix + 'recent'] else: update_time = self.cache_ttl n_available_updates = self.out_of_date_time outdated = DateUtils.is_outdated(now, last_update_date, update_time * 2) if outdated: logger.info(self.__MESSAGES['last_updated_at'].format( last_update_date)) return self.__END_POINTS[pos_prefix + 'recent'] else: logger.info(self.__MESSAGES['last_updated_at'].format( last_update_date)) return self.__END_POINTS[pos_prefix + 'last']
def print(self): dateutil_obj = DateUtils() for cpu_time in self.cpu_times_proto.cpu_times: print("CPU Index: {}".format(cpu_time.cpu_index)) print("统计时间: {}".format( dateutil_obj.timestamp_to_string(cpu_time.timestamp))) print("用户进程耗时: {}(秒)".format(cpu_time.user_mode_time)) print("内核进程耗时: {}(秒)".format(cpu_time.kernel_mode_time)) print("CPU空闲时间: {}(秒)".format(cpu_time.idle_time))
def __str__( self ): #we hard code the first print so that we can avoid having a #trailing newline at the end rtn = DateUtils.format_day( 1 ) + \ "," + self.data[ 1 ].str_without_date() for i in range( 2 , self.numDays+1 ): rtn = rtn + "\n" + \ DateUtils.format_day( i ) + \ "," + self.data[ i ].str_without_date() return rtn
def __init__( self , month , year ): self.month = month self.year = year self.numDays = DateUtils.get_num_days_in_month( month , year ) self.data = [] for i in range( 0 , self.numDays+1 ): self.data.append( DataPoint( year , month , i , 0 , 0 ) )
def post(self): try: # get input data as json and read required fields some_json = request.get_json() lat = to_float(some_json['lat'], 'lat') long = to_float(some_json['long'], 'long') epoch = to_float(some_json['epoch'], 'epoch') orientation = to_float(some_json['orientation'], 'orientation') if (lat < 0 or lat > 90): raise ValueError("ValueError: lat out of range = [0 to 90]") elif (long < -180 or long > 180): raise ValueError( "ValueError: long out of range = [-180 to 180") elif (orientation < -180 or orientation > 180): raise ValueError( "ValueError: orientation out of range = [-180 to 180]") elif (epoch < 0): raise ValueError( "ValueError: epoch out of range = [epoch > 0]") else: # create objects tz_utils = TimeZoneUtils() date_utils = DateUtils(tz_utils) coord_utils = CoordinationUtils(date_utils, lat, long, epoch, orientation) # compute glare and return results return ({'glare': coord_utils.detect_glare()}) except Exception as e: print(e) return ({'Error': str(e)})
def write_month_data_to_file( monthData , commodity ): month = DateUtils.format_month( monthData.month ) year = str( monthData.year ) datafile = "price_data/" + year + " " + month + "/" + commodity + ".csv" #create the new month folder, if necessary if ( not os.path.exists( os.path.dirname( datafile ) ) ): os.makedirs( os.path.dirname( datafile ) ) f = open( datafile , "w" ) f.write( str( monthData ) )
def __get_endpoint(self, last_update_date): """Returns the end-point to call given a date (`/online`, `/recent` or `/last`). Arguments: last_update_date -- the date of the last update the user has saved locally. """ logger = logging.getLogger('__get_endpoint') now = DateUtils.now() now_str = DateUtils.to_iso_date(now) if last_update_date is None: logger.info(self.__MESSAGES['no_last_update']) return self.__END_POINTS['online'] else: update_time = self.cache_ttl n_available_updates = self.out_of_date_time partially_outdated = DateUtils.is_outdated(now, last_update_date, update_time * 2) fully_outdated = DateUtils.is_outdated(now, last_update_date, update_time * n_available_updates) if fully_outdated: logger.info(self.__MESSAGES['outdated_db']) return self.__END_POINTS['online'] elif partially_outdated: logger.info(self.__MESSAGES['last_updated_at'].format( last_update_date)) return self.__END_POINTS['recent'] else: logger.info(self.__MESSAGES['last_updated_at'].format( last_update_date)) return self.__END_POINTS['last']
def read_month_data( month , year , commodity ): rtn = MonthData( month , year ) dir = "price_data/" + str( year ) + " " + DateUtils.format_month( month ) try : file = open( dir + "/" + commodity + ".csv" , "r" ) lines = file.readlines() for line in lines : datapoint = DataPoint.from_csv_month_data( year , month , line ) rtn.set( int( datapoint.get_day() ) , datapoint ) except IOError: #there is no data, so ignore the error and return default #values of 0 for daily and average prices pass return rtn
def parse_log(self): binning_index = {} for FILE in self.files: for line in open (FILE): if re.match (r'^#', line): continue ts = line.split (self.field_seperator)[self.ts_col] try: current_index = self.dataset + '-' + DateUtils (ts, self.timeformat).get_binning_index () except: current_index = '' if current_index: if current_index not in binning_index: binning_index[current_index] = 1 else: binning_index[current_index] = binning_index[current_index] + 1 return binning_index
def update(self, last_updated_date=None): """Returns a list of Crime Servers (either an update to the current feed, or all of it) and the date when the updated occurred. Arguments: last_updated_date -- last updated date, saved locally. It is used to know if the local client is up-to-date, partially outdated or fully outdated regarding to Blueliv Crime Servers' API. """ logger = logging.getLogger('update') url = self.base_url + self.__get_endpoint( DateUtils.to_iso_date(last_updated_date)) updatedAt = None crimeservers = None response = self.get(url) if response is not None and "crimeServers" in response: crimeservers = response["crimeServers"] updatedAt = response["meta"]["updated"] if "meta" in response and "updated" in response["meta"] else None return (crimeservers, updatedAt)
def update(self, last_updated_date=None, pos=False): """Returns a list of Bot IPs and the date when the updated occurred. Arguments: last_updated_date -- last updated date, saved locally. It is used to know if the local client is up-to-date or outdated regarding to Blueliv Bot IPs' API; pos -- flag to choose between Bot IPs POS feed and the normal one. """ logger = logging.getLogger('update') url = self.base_url + self.__get_endpoint( DateUtils.to_iso_date(last_updated_date), pos) updatedAt = None bot_ips = None response = self.get(url) if response is not None and "ips" in response: bot_ips = response["ips"] updatedAt = response["meta"]["updated"] if "meta" in response and "updated" in response["meta"] else None return (bot_ips, updatedAt)
def is_before(self, otherDatapoint): return DateUtils.is_after( int( self._year ) , int( self._month ) , \ int( self._day ) , int( otherDatapoint._year ) , \ int( otherDatapoint._month ) , int( otherDatapoint._day ) )
def is_before( self , otherDatapoint ): return DateUtils.is_after( int( self._year ) , int( self._month ) , \ int( self._day ) , int( otherDatapoint._year ) , \ int( otherDatapoint._month ) , int( otherDatapoint._day ) )