class HrOvertimeByMonth(models.TransientModel): _name = 'hr.overtime.wizard_odt.month' _description = 'Print Monthly Overtime Report' month = fields.Selection([(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December')], 'Month', required=True, default=lambda *a: time.gmtime()[1]) year = fields.Integer('Year', required=True, default=lambda *a: time.gmtime()[0]) @api.multi def print_report(self): datas = { 'ids': self._context.get('active_ids', []) and self._context.get('active_ids', []) or [], 'model': 'hr.employee', 'form': self.read()[0] } return { 'type': 'ir.actions.report.xml', 'report_name': 'overtime_odt', 'context': None, 'datas': datas, }
def InsertSingleEvent(calendar_client, title='bseu-api event', content='study hard', where='in space', start_time=None, end_time=None, ucalendar=None): event = gdata.calendar.data.CalendarEventEntry() event.title = atom.data.Title(text=title) event.content = atom.data.Content(text=content) event.where.append(gdata.calendar.data.CalendarWhere(value=where)) if start_time is None: # Use current time for the start_time and have the event last 1 hour start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime()) end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 3600)) else: start_time = (start_time - timedelta(hours=3)).strftime('%Y-%m-%dT%H:%M:%S.000Z') end_time = (end_time - timedelta(hours=3)).strftime('%Y-%m-%dT%H:%M:%S.000Z') event.when.append(gdata.calendar.data.When(start=start_time, end=end_time)) try: if ucalendar is None: calendar_client.InsertEvent(event) else: calendar_client.InsertEvent(event, ucalendar) except Exception, e: logging.error('import was unsuccessful - skipping: %s' % e)
def test_utcfromtimestamp(self): import time ts = time.time() expected = time.gmtime(ts) got = self.theclass.utcfromtimestamp(ts) self.verify_field_equality(expected, got)
def get_duration(self): return self.user_logs_summary.filter(type='in') and time.strftime( '%H:%M:%S', time.gmtime( self.user_logs_summary.filter( type='in').values('duration').aggregate( sum=Sum('duration'))['sum'].total_seconds())) or None
def register_user(request): print "user is trying to register" username1 = request.POST['username'] password1 = request.POST['password'] lat = request.POST['userLatitude'] longi = request.POST['userLongitude'] ib = request.POST['blurb'] img = request.POST['image'] registration = '' if User.objects.filter(username=username1).count(): registration = 'user_exists' else: print "username does not exist, attempting to register user" u = User(username=username1)#, email=em) u.set_password(password1) u.save() prof = Profile(info_blurb = ib, pub_date = datetime.now(), user = u) prof.latitude = lat prof.longitude = longi print 'attempting to save image to directory' img_filename = prof.user.username+'_'+str(calendar.timegm(time.gmtime()))+'.jpg' prof.photo = ContentFile(b64decode(img), img_filename) prof.save() user = authenticate(username=username1, password=password1) if registration is '': if user is not None: registration= 'success' else: registration= 'failure' json_data = json.dumps({"registration":registration}) print json_data return HttpResponse(json_data, content_type="application/json")
def main(): parser = argparse.ArgumentParser("Online Khabar Scrapper") parser.add_argument("-n", "--news_link", default="https://www.onlinekhabar.com", metavar="LINK", help="News Link") parser.add_argument("-s", "--source", default="onlinekhabar", metavar="SOURCE", help="News source name") parser.add_argument("-d", "--given_date", default=None, metavar="DATE", help="Date Format : 2020/04") parser.add_argument("-sp", "--start_page", default=1, type=int, metavar="PAGE", help="Starting page to scrap") parser.add_argument("-ep", "--end_page", default=15, type=int, metavar="PAGE", help="End page to scrap") args = parser.parse_args() news_link = args.news_link news_source_name = args.source start_page = args.start_page page_num = args.end_page # Take today's date if not given on arguments given_date = args.given_date if args.given_date else date.today().strftime("%Y/%m") logger.info("Scrapping at least {} pages from each categories ahead of {} date".format(page_num-start_page, given_date)) start_time = time.time() scrappy = Scrapper(news_link=news_link, source=news_source_name, given_date=given_date, start_page=start_page, page_num=page_num) scrappy.extractContent() seconds = time.time() - start_time logger.info("Total time taken to scrap : {}".format(time.strftime("%H:%M:%S",time.gmtime(seconds))))
def wake_up_user(user): while user.start <= calendar.timegm( time.gmtime()) < user.start + user.threshold: if door_status: time.sleep(10) client.publish(TOPIC_ALARM + userid, payload="Wake up!") time.sleep(180) # 3 min to move his lazy ass to the toilet break time.sleep(5)
def __init__(self, user, password, useDigest=False): self._user = user self._created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time())) self._nonce = sha.new(str(random.random())).digest() if (useDigest): self._passwordType = self.PASSWORD_DIGEST_TYPE digest = sha.new(self._nonce + self._created + password).digest() # binascii.b2a_base64 adds a newline at the end self._password = binascii.b2a_base64(digest)[:-1] else: self._passwordType = self.PASSWORD_PLAIN_TYPE self._password = password
print(now) print(now.month) print(now.day) print(now.year) print(now.minute) print(now.second) print(now.microsecond) # MERGING DATE AND TIMES from datetime import datetime, time, date noon = time(12) this_day = date.today() noon_today = datetime.combine(this_day, noon) print(noon_today) print(noon_today.date()) print(noon_today.time()) # USING ABSOLUTE TIME (time module) # UNIX time counts the number of seconds since January 1st 1970 import time # this is not the same module as "from datetime import time" now = time.time() print(now) # convert an epoch value into a string... print(time.ctime(now)) print(time.localtime(now)) print(time.gmtime(now)) # you can also convert a struct_time object to epoch seconds tm = time.localtime(now) print(time.mktime(tm))
# system's time zone, and gmtime() provides it in UTC. # Note: UTC is the time standard commonly used across the world. It is not a # time zone but a time standard that is the basis for civil time and time # zones worldwide. This means that no country or territory officially uses # UTC as a local time. Formerly GMT (Greenwich Mean Time - is now a time zone). print(time.localtime(now)) # time.struct_time(tm_year=2017, tm_mon=11, tm_mday=7, tm_hour=16, tm_min=23, # tm_sec=56, tm_wday=1, tm_yday=311, tm_isdst=0) print(time.localtime()) # time.struct_time(tm_year=2017, tm_mon=11, tm_mday=7, tm_hour=16, tm_min=23, # tm_sec=56, tm_wday=1, tm_yday=311, tm_isdst=0) print(time.gmtime(now)) # time.struct_time(tm_year=2017, tm_mon=11, tm_mday=8, tm_hour=0, tm_min=23, # tm_sec=56, tm_wday=2, tm_yday=312, tm_isdst=0) print(time.gmtime()) # time.struct_time(tm_year=2017, tm_mon=11, tm_mday=8, tm_hour=0, tm_min=23, # tm_sec=56, tm_wday=2, tm_yday=312, tm_isdst=0) print(type(time.localtime(now))) # <class 'time.struct_time'> t = time.localtime() print(('Year {0[0]}, Month {0[1]}, Day {0[2]}, Hour {0[3]}, Minute {0[4]}, ' 'Second {0[5]}, Weekday {0[6]}, Yearday {0[7]}, DST {0[8]}').format(t)) # Year 2017, Month 11, Day 7, Hour 16, Minute 28, Second 23, Weekday 1, # Yearday 311, DST 0
def handle(self): # self.request is the TCP socket connected to the client logger.debug(self.client_address) if time_synchronized: curtime = time.strftime(DATE_FORMAT, time.gmtime()) self.request.sendall(curtime)
def parse(self, response): data = json.loads(response.body) pageNo = int(response.url.split('=')[-1]) path = data['hits'] no = len(path) for i in range(0, no): item = HousingItem() count = len(path[i]['inventory_configs']) for j in range(0, count): item['data_id'] = path[i]['inventory_configs'][j]['id'] item['txn_type'] = path[i]['type'] try: item['Building_name'] = path[i]['name'] except: item['Building_name'] = 'None' item['property_type'] = 'Residential' dates = path[i]['date_added'].replace('T', ' ').replace('Z', '') item['listing_date'] = dt.strftime( dt.strptime(dates, '%Y-%m-%d %H:%M:%S'), '%m/%d/%Y %H:%M:%S') loc = path[i]['location_coordinates'] item['lat'] = loc.split(',')[0] item['longt'] = loc.split(',')[-1] item['Selling_price'] = path[i]['inventory_configs'][j][ 'price'] item['Monthly_Rent'] = '0' item['Bua_sqft'] = path[i]['inventory_configs'][j]['area'] item['config_type'] = str(path[i]['inventory_configs'][j] ['number_of_bedrooms']) + 'BHK' pos = path[i]['inventory_configs'][j]['completion_date'] item['Possession'] = time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(pos)) item['price_per_sqft'] = path[i]['inventory_configs'][j][ 'per_sqft_rate'] item['price_on_req'] = path[i]['inventory_configs'][j][ 'price_on_request'] try: item['name_lister'] = path[i]['contact_persons_info'][0][ 'name'] except: item['name_lister'] = 'None' item['city'] = path[i]['polygons_hash']['city']['name'] item['sublocality'] = path[i]['polygons_hash']['sublocality'][ 'name'] if item['sublocality'] == None: item['sublocality'] = 'None' try: item['updated_date'] = time.strftime( '%m/%d/%Y %H:%M:%S', time.gmtime(path[i]['updated_at'])) except: item['updated_date'] = item['listing_date'] try: item['locality'] = path[i]['display_neighbourhood'][1] except: item['locality'] = 'None' item['scraped_time'] = dt.now().strftime('%m/%d/%Y %H:%M:%S') ''' Assignning Default values ''' item['carpet_area'] = '0' item['management_by_landlord'] = 'None' item['areacode'] = 'None' item['mobile_lister'] = 'None' item['google_place_id'] = 'None' item['Launch_date'] = '0' item['age'] = 'None' item['address'] = 'None' item['platform'] = 'housing' item['Status'] = 'None' item['listing_by'] = 'None' item['Details'] = 'None' if (((not item['Monthly_Rent'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')) or ((not item['Selling_price'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')) or ((not item['price_per_sqft'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0'))): item['quality4'] = 1 elif (((not item['price_per_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')) or ((not item['Selling_price'] == '0') and (not item['Bua_sqft'] == '0') and (not item['lat'] == '0')) or ((not item['Monthly_Rent'] == '0') and (not item['Bua_sqft'] == '0') and (not item['lat'] == '0')) or ((not item['Selling_price'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None')) or ((not item['Monthly_Rent'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None'))): item['quality4'] = 0.5 else: item['quality4'] = 0 if ((not item['Building_name'] == 'None') and (not item['listing_date'] == '0') and (not item['txn_type'] == 'None') and (not item['property_type'] == 'None') and ((not item['Selling_price'] == '0') or (not item['Monthly_Rent'] == '0'))): item['quality1'] = 1 else: item['quality1'] = 0 if ((not item['Launch_date'] == '0') and (not item['Possession'] == '0')): item['quality2'] = 1 else: item['quality2'] = 0 if ((not item['mobile_lister'] == 'None') or (not item['listing_by'] == 'None') or (not item['name_lister'] == 'None')): item['quality3'] = 1 else: item['quality3'] = 0 yield item if data['is_last_page'] == False: next_url = 'https://buy.housing.com//api/v3/buy/index/filter?source=web&poly=1ca99c33e3d8b987ccf1&sort_key=date_added&total=27998&np_total_count=1888&resale_total_count=26110&np_offset=0&resale_offset=0&is_last_page=false&project_flat_config_count=5244&negative_aggregation={}&show_collections=true&show_aggregations=true&placeholder_ids=2,3,6,7&p=' + str( pageNo + 1) yield Request(next_url, callback=self.parse)
datetime.time(12, 0) >>> 10.4.2 timeモジュールの使い方 >>> import time >>> now = time.time() >>> now 1516083078.363716 >>> time.ctime(now) 'Tue Jan 16 14:11:18 2018' >>> time.localtime(now) time.struct_time(tm_year=2018, tm_mon=1, tm_mday=16, tm_hour=14, tm_min=11, tm_sec=18, tm_wday=1, tm_yday=16, tm_isdst=0) >>> time.gmtime(now) time.struct_time(tm_year=2018, tm_mon=1, tm_mday=16, tm_hour=6, tm_min=11, tm_sec=18, tm_wday=1, tm_yday=16, tm_isdst=0) >>> tm = time.localtime(now) >>> time.mktime(tm0 ... ... ) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'tm0' is not defined >>> time.mktime(tm) 1516083078.0 >>> 10.4.3 日時の読み書き
print(noon) # 12:00:00 print(noon.hour) # 12 print(noon.minute) # 0 print(noon.second) # 0 print(noon.microsecond) # 0 import time # 1970/1/1일 자정 이후 시간의 초를 사용 (epoch) now = time.time() print(now) # 1577878707.9758263 print(time.ctime(now)) # epoch 값을 문자열로 # Wed Jan 1 20:39:50 2020 print(time.localtime(now)) # 시간을 시스템 표준 시간대로 print(time.gmtime(now)) # 시간을 UTC로 제공한다. # time.struct_time(tm_year=2020, tm_mon=1, tm_mday=1, tm_hour=20, tm_min=42, tm_sec=29, tm_wday=2, tm_yday=1, tm_isdst=0) tm = time.localtime(now) print(time.mktime(tm)) # 1577878949.0 ftm = "It's %A, %B %d, %Y, locatime %I:%M:%S%p" t = time.localtime() print(time.strftime( ftm, t)) # It's Wednesday, January 01, 2020, locatime 08:47:17PM ''' *** strftime() 출력 지정자 *** %Y : 년 %m : 월 %B : 월 이름 %b : 월 축약 이름
from datetime import date, datetime, time, timedelta a = date(2017, 8, 9) b = datetime(2017, 8, 9) c = b.today() - b d = time(12, 34, 56) e = b.today() + timedelta(days=7, hours=1) print(a, b, c, d, d.tzname(), e) import time a = time.gmtime() b = time.localtime() c = time.time() print(a, b, c) for i in range(10): print(i) time.sleep(1)
def edit_pic(request): print "user is trying to edit profile pic" username1 = request.POST['username'] img = request.POST['image'] prof = Profile.objects.get(user__username=username1) #Check if profile photo file already exists, if it does, delete it #before saving new photo of the same name fullname = os.path.join(settings.MEDIA_ROOT[:-6], prof.photo.url) if os.path.exists(fullname): os.remove(fullname) prof.photo = ContentFile(b64decode(img), prof.user.username+'_'+str(calendar.timegm(time.gmtime()))+'.jpg') prof.save() json_data = json.dumps({"edit_pic":"success"}) return HttpResponse(json_data, content_type="application/json")
some_day.isoformat() now = datetime.now() now.minute now.microsecond noon = time(12) this_day = date.today() noon_today = datetime.combine(this_day, noon) noon_today noon_today.date() noon_today.time() import time now = time.time() now time.ctime(now) time.localtime(now) time.gmtime(now) tm = time.localtime(now) time.mktime(tm) time.ctime(time.time()) fmt = "It's %A, %B %d, %Y, local time %I:%M:%S%p" t = time.localtime() t time.strftime(fmt, t) fmt = "%Y-%m-%d" time.strptime("2015-06-02", fmt) import locale from datetime import date halloween = date(2015, 10, 31) for lang_country in ['ko-kr', 'en-us']: locale.setlocale(locale.LC_TIME, lang_country)
tmStr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) print(tmStr) dt = datetime.now() print(type(dt), dt) print(dt.year, dt.month, dt.day, dt.second, dt.microsecond) # 2 日期字符串--> 日期 s = '2015-12-21 15:01:28' timeTuple = datetime.strptime(s, '%Y-%m-%d %H:%M:%S') print(timeTuple) print(timeTuple.timestamp()) ## 3 时间戳 日期---》时间 tm = time.gmtime(timeTuple.timestamp()) print(tm, int(time.time())) print(time.ctime(timeTuple.timestamp()), time.ctime(time.time())) # timestamp to time tuple in UTC timestamp = 1226527167.595983 time_tuple = time.gmtime(timestamp) # second print(repr(time_tuple)) # 4 日期相加减 now = datetime.now() # datetime.datetime(2015, 12, 16, 15, 6, 37, 420000) dayOfweek = now.isoweekday() if dayOfweek == 1: # Monday last_time = now + timedelta(days=-3) else: last_time = now + timedelta(hours=-1) print(last_time)
def parse(self, response): data = None try: data1 = (response.body).decode("utf-8") data = json.loads(data1) # pageNo = int(response.url.split('=')[-1]) path = data['hits'] item = HousingItem() no = len(path) for i in range(0, no): try: count = len(path[i]['inventory_configs']) for j in range(0, count): item['data_id'] = path[i]['inventory_configs'][j]['id'] item['txn_type'] = path[i]['type'] if 'project' in item['txn_type'] or item[ 'txn_type'] is None or item[ 'txn_type'] == '' or item[ 'txn_type'] == ' ': item['txn_type'] = 'Sale' try: buildname = path[i]['building_name'] if 'N/A' == buildname.upper( ) or 'N.A' == buildname.upper( ) or 'NA' == buildname.upper( ) or buildname == '' or buildname == ' ' or buildname == 'Na' or '..' in buildname: buildname = 'None' item['Building_name'] = buildname except: item['Building_name'] = 'None' item['property_type'] = 'Residential' dates = path[i]['date_added'].split('T')[ 0] # .replace('T', ' ').replace('Z', '') if dates is not None: item['listing_date'] = dt.strftime( dt.strptime(dates, '%Y-%m-%d'), '%m/%d/%Y') loc = path[i]['location_coordinates'] item['lat'] = loc.split(',')[0] item['longt'] = loc.split(',')[1] try: item['Selling_price'] = path[i][ 'inventory_configs'][j]['price'] if item['Selling_price'] is None: item['Selling_price'] = 0 except: item['Selling_price'] = 0 item['Bua_sqft'] = path[i]['inventory_configs'][j][ 'area'] item['config_type'] = str( path[i]['inventory_configs'][j] ['number_of_bedrooms']) + 'BHK' try: pos = path[i]['inventory_configs'][j][ 'completion_date'] item['Possession'] = time.strftime( '%m/%d/%Y', time.gmtime(pos)) except: print('') try: item['price_per_sqft'] = path[i][ 'inventory_configs'][j]['per_sqft_rate'] except: item['price_per_sqft'] = 0 item['price_on_req'] = path[i]['inventory_configs'][j][ 'price_on_request'] try: item['name_lister'] = path[i][ 'contact_persons_info'][0]['name'] except: item['name_lister'] = 'None' else: # contact_person_id try: contactperson = int( path[i]['contact_persons_info'][0] ['contact_person_id']) if contactperson == 1: item['listing_by'] = 'Agent' elif contactperson == 2: item['listing_by'] = 'Owner' elif contactperson == 3: item['listing_by'] = 'Builder' else: item['listing_by'] = 'Housing User' except: item['listing_by'] = 'None' # try: # item['city'] = path[i]['polygons_hash']['city']['name'] # except: item['city'] = 'Navi Mumbai' item['sublocality'] = path[i]['polygons_hash'][ 'sublocality']['name'] if item['sublocality'] is None or item[ 'sublocality'] == '' or item[ 'sublocality'] == ' ': item['sublocality'] = 'None' try: item['updated_date'] = time.strftime( '%m/%d/%Y', time.gmtime(path[i]['updated_at'])) except: item['updated_date'] = item['listing_date'] try: item['locality'] = path[i][ 'display_neighbourhood'][1] except: item['locality'] = 'None' item['scraped_time'] = dt.now().strftime('%m/%d/%Y') if item['Possession'] < item['scraped_time']: item['Possession'] = item['scraped_time'] item['carpet_area'] = '0' item['management_by_landlord'] = 'None' item['areacode'] = 'None' item['mobile_lister'] = 'None' item['google_place_id'] = 'None' item['Launch_date'] = '0' item['age'] = '0' item['address'] = 'None' item['Monthly_Rent'] = '0' item['platform'] = 'Housing' try: stat = str(path[i]['is_uc_property']) print("Status", stat) if stat is None: item['Status'] = 'Ready To Move' else: if 'alse' in stat.lower(): item['Status'] = 'Ready To Move' elif 'rue' in stat.lower(): item['Status'] = 'Under Construction' except: item['Status'] = 'None' item['Details'] = 'None' if (((not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')) or ((not item['Selling_price'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')) or ((not item['price_per_sqft'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0'))): item['quality4'] = 1 elif (((not item['price_per_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')) or ((not item['Selling_price'] == '0') and (not item['Bua_sqft'] == '0') and (not item['lat'] == '0')) or ((not item['Bua_sqft'] == '0') and (not item['lat'] == '0')) or ((not item['Selling_price'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None')) or ((not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None'))): item['quality4'] = 0.5 else: item['quality4'] = 0 if ((not item['Building_name'] == 'None') and (not item['listing_date'] == '0') and (not item['txn_type'] == 'None') and (not item['property_type'] == 'None') and ((not item['Selling_price'] == '0'))): item['quality1'] = 1 else: item['quality1'] = 0 if ((not item['Launch_date'] == '0') and (not item['Possession'] == '0')): item['quality2'] = 1 else: item['quality2'] = 0 if ((not item['mobile_lister'] == 'None') or (not item['listing_by'] == 'None') or (not item['name_lister'] == 'None')): item['quality3'] = 1 else: item['quality3'] = 0 except Exception as e: print(e) finally: yield item except Exception as e: print(e) next_page = str(data['is_last_page']) print(next_page) if next_page is not None: if 'false' in next_page.lower(): pageNo = int(response.url.split('&p=')[1]) next_url = str( response.url.split('&p=')[0]) + '&p=' + str(pageNo + 1) yield Request(next_url, callback=self.parse, dont_filter=True)
async def showme(self, ctx): with open('cogs/payouts.json', 'r') as json_file: parsed = json.load(json_file) ruorder = [] euorder = [] ukorder = [] estorder = [] cstorder = [] pstorder = [] self.today = date.today() current_time = time.strftime('%H:%M:%S', time.gmtime()) if ctx.invoked_subcommand is None: for p in parsed['squad']: ordname = p['order'] if ordname == 'ruorder': members = ', '.join(map(str, p['members'])) ruorder.append(members) ruflag = p['flag'] rutz = p['tzname'] ruutc = datetime.strptime(p['utctime'], '%H:%M:%S') - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') < datetime.strptime( current_time, '%H:%M:%S'): rupayout = ' :moneybag:' else: rupayout = ' - :clock130: ' + str(ruutc) elif ordname == 'euorder': members = ', '.join(map(str, p['members'])) euorder.append(members) euflag = p['flag'] eutz = p['tzname'] euutc = datetime.strptime(p['utctime'], '%H:%M:%S') - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') < datetime.strptime( current_time, '%H:%M:%S'): eupayout = ' :moneybag:' else: eupayout = ' - :clock130: ' + str(euutc) elif ordname == 'ukorder': members = ', '.join(map(str, p['members'])) ukorder.append(members) ukflag = p['flag'] uktz = p['tzname'] ukutc = datetime.strptime(p['utctime'], '%H:%M:%S') - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') < datetime.strptime( current_time, '%H:%M:%S'): ukpayout = ' :moneybag:' else: ukpayout = ' - :clock130: ' + str(ukutc) elif ordname == 'estorder': members = ', '.join(map(str, p['members'])) estorder.append(members) usflag = p['flag'] esttz = p['tzname'] estutc = datetime.strptime(p['utctime'], '%H:%M:%S') - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') < datetime.strptime( current_time, '%H:%M:%S'): estpayout = ' :moneybag:' else: estpayout = ' - :clock130: ' + str(estutc) elif ordname == 'cstorder': members = ', '.join(map(str, p['members'])) cstorder.append(members) csttz = p['tzname'] cstutc = (datetime.strptime(p['utctime'], '%H:%M:%S') + timedelta(days=1)) - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') > datetime.strptime( current_time, '%H:%M:%S'): cstpayout = ' :moneybag:' else: cstpayout = ' - :clock130: ' + str(cstutc) else: members = ', '.join(map(str, p['members'])) pstorder.append(members) psttz = p['tzname'] psttz = p['tzname'] pstutc = (datetime.strptime(p['utctime'], '%H:%M:%S') + timedelta(days=1)) - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') > datetime.strptime( current_time, '%H:%M:%S'): pstpayout = ' :moneybag:' else: pstpayout = ' - :clock130: ' + str(pstutc) await self.bot.say("Payout list:\n" + ruflag + rutz + " - " + ', '.join(ruorder) + str(rupayout) + "\n" + euflag + eutz + " - " + ', '.join(euorder) + str(eupayout) + "\n" + ukflag + uktz + " - " + ', '.join(ukorder) + str(ukpayout) + "\n" + usflag + esttz + " - " + ', '.join(estorder) + str(estpayout) + "\n" + usflag + csttz + " - " + ', '.join(cstorder) + str(cstpayout) + "\n" + usflag + psttz + " - " + ', '.join(pstorder) + str(pstpayout) + "\n") await send_cmd_help(ctx)
noon_today = datetime.combine(this_day, noon) noon_today.date() noon_today.time() # time (Unix Time) import time now = time.time() # 1391488263.664645 time.ctime(now) # Mon Feb 3 22:31:03 2014 # to struc_time from Unix Time time.localtime( now ) # standard time fo system (Not recommended because of including summer time) time.gmtime(now) # UTC (recommended) # to Unix Time from struct_time tm = time.localtime(now) time.mktime(tm) # strftime() # form struct_time and return string # %Y 1900-... # %m 01-12 # %B January,... # %b Jan, ... # %d 01-31 # %A Sunday, ... # %a Sun, ... # %H 00-23
from datetime import datetime, time import time import ts as ts now = datetime.now() timestamp = datetime.timestamp(now) print("timestamp =", timestamp) ts = time.gmtime() print(time.strftime("%Y-%m-%d", ts))
def main(args): logfilename = os.path.join(args.logdir,'serial.log') oldlogfilename = os.path.join(args.logdir,'serial.log.0') current = Weather() h = 139 # elevation in meters if args.days > 7: print "WARNING: %s days requested; log may contain 7-14 days of data" % args.days # copy DATA lines to temporary file, concatenating current and former logfiles t = tempfile.TemporaryFile() # to have a named file for testing: # t = tempfile.NamedTemporaryFile(delete=False) logfile = open(oldlogfilename,'r') for line in logfile: if re.match("(.*)DATA(.*)", line): t.write(line) logfile.close() logfile = open(logfilename,'r') for line in logfile: if re.match("(.*)DATA(.*)", line): t.write(line) logfile.close() # read from tempfile into numpy array for each parameter t.seek(0) temptemp = np.asarray(re.findall('(\d+) DATA: T= (.+) degC',t.read()), dtype=np.float64) #temptemp[np.where(temptemp<MINTEMP)] = np.nan temp = np.ma.masked_less(temptemp, current.MINTEMP) current.temp = temp[len(temp)-1,1] # most recent temp now = int(temp[len(temp)-1,0]) # in Unix seconds if args.verbose: print "Timezone offset: %s" % current.timezone # store as Python datetime, in local time, naive format with no real tzinfo set current.time = dates.num2date(dates.epoch2num(now-current.timezone)) current.max = np.max(temp[temp[:,0] > (now-86400),1]) current.min = np.min(temp[temp[:,0] > (now-86400),1]) if args.verbose: print "Temperature records: %s" % len(temp) t.seek(0) pressure = np.asarray(re.findall('(\d+) DATA: P= (\d+) Pa',t.read()), dtype=np.float64) current.pressure = sealevel(pressure[len(pressure)-1,1]/100,h) if args.verbose: print "Pressure records: %s" % len(pressure) t.seek(0) humid = np.asarray(re.findall('(\d+) DATA: H= (\d+) %',t.read()), dtype=np.int) t.close() current.humid = humid[len(humid)-1,1] if args.verbose: print "Humidity records: %s" % len(humid) # set start time to midnight local time, # of days ago specified start = (np.floor((now-current.timezone)/86400.0) - args.days)*86400 + current.timezone if args.verbose: print "Current timestamp: %s" % now if args.verbose: print "Start timestamp: %s" % start temp=temp[temp[:,0]>start,:] pressure=pressure[pressure[:,0]>start,:] humid=humid[humid[:,0]>start,:] m=temp[0,0] if args.verbose: print "First actual timestamp: %s" % m current.report() current.save_html() fig = Figure(figsize=(8,8)) # ensure that all 3 plots are on same x-axis end = (np.floor((now)/86400.0) + 1)*86400 if args.verbose: print "last plot time: %f, %s" % (end, time.strftime("%a %d %b %Y %H:%M:%S",time.gmtime(end))) xlim=(dates.epoch2num(start - current.timezone),dates.epoch2num(end)) # Temperature plot ax = fig.add_subplot(311) ax.plot(dates.epoch2num(temp[:,0]-current.timezone),temp[:,1]) ax.set_xlim(xlim) ax.set_ylabel(u'Temp (°C)') ax2 = ax.twinx() clim = pyplot.get(ax,'ylim') ax2.set_ylim(c2f(clim[0]),c2f(clim[1])) datelabels(ax) ax2.set_ylabel(u'Temp (°F)') # Humidity plot ax = fig.add_subplot(312) ax.plot(dates.epoch2num(humid[:,0]-current.timezone),humid[:,1],'-') ax.set_xlim(xlim) ax.set_ylim(0,100) ax.set_ylabel('Humidity (%)') ax2 = ax.twinx() ax2.set_ylim(0,100) datelabels(ax) ax2.set_ylabel('Humidity (%)') # Pressure plot ax = fig.add_subplot(313) ax.plot(dates.epoch2num(pressure[:,0]-current.timezone),sealevel(pressure[:,1],h)/100,'-') ax.set_xlim(xlim) ax.set_ylabel('Pressure (mbar)') ax.set_xlabel('local time (%s)' % current.TZ) ax2 = ax.twinx() clim = pyplot.get(ax,'ylim') ax2.set_ylim(clim[0]*0.02954,clim[1]*0.02954) datelabels(ax) ax.xaxis.set_major_locator( dates.HourLocator(interval=12) ) ax.xaxis.set_major_formatter( dates.DateFormatter('%H:%M') ) ax2.set_ylabel('P (inches Hg)') canvas = FigureCanvasAgg(fig) canvas.print_figure(os.path.join(args.outdir,'plot.png'), dpi=80) canvas.print_figure(os.path.join(args.outdir,'plot.pdf')) if args.upload: # upload static html file & images os.system('sitecopy -u weather') if args.show: # show the plot # doesn't work with FigureCanvasAgg #pyplot.show() # Linux (or X11 in OS X) os.system("display %s" % os.path.join(args.outdir,'plot.png'))
async def shipper(self, ctx): with open('cogs/payouts.json', 'r') as json_file: parsed = json.load(json_file) indorder = [] taiorder = [] saorder = [] euorder = [] pstorder = [] estorder = [] cstorder = [] mstorder = [] akorder = [] self.today = date.today() current_time = time.strftime('%H:%M:%S', time.gmtime()) if ctx.invoked_subcommand is None: for p in parsed['fleet']: ordname = p['order'] if ordname == 'indorder': members = ', '.join(map(str, p['members'])) indorder.append(members) indtz = p['tzname'] indutc = datetime.strptime(p['utctime'], '%H:%M:%S') - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') < datetime.strptime( current_time, '%H:%M:%S'): indpayout = ' :moneybag:' else: indpayout = ' - :clock130: ' + str(indutc) if ordname == 'taiorder': members = ', '.join(map(str, p['members'])) taiorder.append(members) taitz = p['tzname'] taiutc = datetime.strptime(p['utctime'], '%H:%M:%S') - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') < datetime.strptime( current_time, '%H:%M:%S'): taipayout = ' :moneybag:' else: taipayout = ' - :clock130: ' + str(taiutc) if ordname == 'saorder': members = ', '.join(map(str, p['members'])) saorder.append(members) satz = p['tzname'] sautc = datetime.strptime(p['utctime'], '%H:%M:%S') - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') < datetime.strptime( current_time, '%H:%M:%S'): sapayout = ' :moneybag:' else: sapayout = ' - :clock130: ' + str(sautc) elif ordname == 'euorder': members = ', '.join(map(str, p['members'])) euorder.append(members) eutz = p['tzname'] euutc = datetime.strptime(p['utctime'], '%H:%M:%S') - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') < datetime.strptime( current_time, '%H:%M:%S'): eupayout = ' :moneybag:' else: eupayout = ' - :clock130: ' + str(euutc) elif ordname == 'estorder': members = ', '.join(map(str, p['members'])) estorder.append(members) esttz = p['tzname'] estutc = (datetime.strptime(p['utctime'], '%H:%M:%S') + timedelta(days=1)) - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') > datetime.strptime( current_time, '%H:%M:%S'): estpayout = ' :moneybag:' else: estpayout = ' - :clock130: ' + str(estutc) elif ordname == 'cstorder': members = ', '.join(map(str, p['members'])) cstorder.append(members) csttz = p['tzname'] cstutc = (datetime.strptime(p['utctime'], '%H:%M:%S') + timedelta(days=1)) - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') > datetime.strptime( current_time, '%H:%M:%S'): cstpayout = ' :moneybag:' else: cstpayout = ' - :clock130: ' + str(cstutc) elif ordname == 'mstorder': members = ', '.join(map(str, p['members'])) mstorder.append(members) msttz = p['tzname'] mstutc = (datetime.strptime(p['utctime'], '%H:%M:%S') + timedelta(days=1)) - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') > datetime.strptime( current_time, '%H:%M:%S'): mstpayout = ' :moneybag:' else: mstpayout = ' - :clock130: ' + str(mstutc) elif ordname == 'akorder': members = ', '.join(map(str, p['members'])) akorder.append(members) aktz = p['tzname'] akutc = (datetime.strptime(p['utctime'], '%H:%M:%S') + timedelta(days=1)) - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') > datetime.strptime( current_time, '%H:%M:%S'): akpayout = ' :moneybag:' else: akpayout = ' - :clock130: ' + str(akutc) elif ordname == 'pstorder': members = ', '.join(map(str, p['members'])) pstorder.append(members) psttz = p['tzname'] pstutc = (datetime.strptime(p['utctime'], '%H:%M:%S') + timedelta(days=1)) - datetime.strptime( current_time, '%H:%M:%S') if datetime.strptime(p['utctime'], '%H:%M:%S') > datetime.strptime( current_time, '%H:%M:%S'): pstpayout = ' :moneybag:' else: pstpayout = ' - :clock130: ' + str(pstutc) await self.bot.say("Payout list:\n" + indtz + " - " + ', '.join(indorder) + str(indpayout) + "\n" + taitz + " - " + ', '.join(taiorder) + str(taipayout) + "\n" + satz + " - " + ', '.join(saorder) + str(sapayout) + "\n" + eutz + " - " + ', '.join(euorder) + str(eupayout) + "\n" + esttz + " - " + ', '.join(estorder) + str(estpayout) + "\n" + csttz + " - " + ', '.join(cstorder) + str(cstpayout) + "\n" + msttz + " - " + ', '.join(mstorder) + str(mstpayout) + "\n" + psttz + " - " + ', '.join(pstorder) + str(pstpayout) + "\n" + aktz + " - " + ', '.join(akorder) + str(akpayout) + "\n") await send_cmd_help(ctx)
print('Разделение date():', noon_today.date()) print('Разделение time():', noon_today.time()) print('----------------------------') # Модуль time (но это не тот модуль из модуля datetime): # ПУТАНИЦА ;) # time работает с временем epoch - количеством секунд от полуночи 1 января 1970го года import time now = time.time() # Текущее время epoch print('Текущее время epoch:', now) # преобразуем строку epoch в строку нормального времени (gmtime() и localtim()) # лучше использовать всегда UTC, потому что это абсолютное время print(time.ctime(now)) print('Текущее время с учетом моего часового пояса (структура struct_time): ', time.localtime()) print('Текущее время UTC (структура struct_time): ', time.gmtime()) # конвертируем обратно в epoch (mktime): tm = time.localtime(now) print(time.mktime(tm)) # Преобразование epoch в строку по формату import time fmt_usa = "It's %A, %B %d, %Y, local time %I:%M:%S %p" fmt_rus = "It's %A, %d.%m.%Y, local time %H:%M:%S" t = time.localtime() print("Структура:", t) print("По формату:", time.strftime(fmt_rus, t)) import time fmt = "%Y-%m-%d" #print(time.strptime("2020 01 29", fmt)) # ERROR, потому что пробелы вместо дефисов
def main(args): logfilename = os.path.join(args.logdir, 'serial.log') oldlogfilename = os.path.join(args.logdir, 'serial.log.0') current = Weather() h = 139 # elevation in meters if args.days > 7: print "WARNING: %s days requested; log may contain 7-14 days of data" % args.days # copy DATA lines to temporary file, concatenating current and former logfiles t = tempfile.TemporaryFile() # to have a named file for testing: # t = tempfile.NamedTemporaryFile(delete=False) logfile = open(oldlogfilename, 'r') for line in logfile: if re.match("(.*)DATA(.*)", line): t.write(line) logfile.close() logfile = open(logfilename, 'r') for line in logfile: if re.match("(.*)DATA(.*)", line): t.write(line) logfile.close() # read from tempfile into numpy array for each parameter t.seek(0) temptemp = np.asarray(re.findall('(\d+) DATA: T= (.+) degC', t.read()), dtype=np.float64) #temptemp[np.where(temptemp<MINTEMP)] = np.nan temp = np.ma.masked_less(temptemp, current.MINTEMP) current.temp = temp[len(temp) - 1, 1] # most recent temp now = int(temp[len(temp) - 1, 0]) # in Unix seconds if args.verbose: print "Timezone offset: %s" % current.timezone # store as Python datetime, in local time, naive format with no real tzinfo set current.time = dates.num2date(dates.epoch2num(now - current.timezone)) current.max = np.max(temp[temp[:, 0] > (now - 86400), 1]) current.min = np.min(temp[temp[:, 0] > (now - 86400), 1]) if args.verbose: print "Temperature records: %s" % len(temp) t.seek(0) pressure = np.asarray(re.findall('(\d+) DATA: P= (\d+) Pa', t.read()), dtype=np.float64) current.pressure = sealevel(pressure[len(pressure) - 1, 1] / 100, h) if args.verbose: print "Pressure records: %s" % len(pressure) t.seek(0) humid = np.asarray(re.findall('(\d+) DATA: H= (\d+) %', t.read()), dtype=np.int) t.close() current.humid = humid[len(humid) - 1, 1] if args.verbose: print "Humidity records: %s" % len(humid) # set start time to midnight local time, # of days ago specified start = (np.floor((now - current.timezone) / 86400.0) - args.days) * 86400 + current.timezone if args.verbose: print "Current timestamp: %s" % now if args.verbose: print "Start timestamp: %s" % start temp = temp[temp[:, 0] > start, :] pressure = pressure[pressure[:, 0] > start, :] humid = humid[humid[:, 0] > start, :] m = temp[0, 0] if args.verbose: print "First actual timestamp: %s" % m current.report() current.save_html() fig = Figure(figsize=(8, 8)) # ensure that all 3 plots are on same x-axis end = (np.floor((now) / 86400.0) + 1) * 86400 if args.verbose: print "last plot time: %f, %s" % ( end, time.strftime("%a %d %b %Y %H:%M:%S", time.gmtime(end))) xlim = (dates.epoch2num(start - current.timezone), dates.epoch2num(end)) # Temperature plot ax = fig.add_subplot(311) ax.plot(dates.epoch2num(temp[:, 0] - current.timezone), temp[:, 1]) ax.set_xlim(xlim) ax.set_ylabel(u'Temp (°C)') ax2 = ax.twinx() clim = pyplot.get(ax, 'ylim') ax2.set_ylim(c2f(clim[0]), c2f(clim[1])) datelabels(ax) ax2.set_ylabel(u'Temp (°F)') # Humidity plot ax = fig.add_subplot(312) ax.plot(dates.epoch2num(humid[:, 0] - current.timezone), humid[:, 1], '-') ax.set_xlim(xlim) ax.set_ylim(0, 100) ax.set_ylabel('Humidity (%)') ax2 = ax.twinx() ax2.set_ylim(0, 100) datelabels(ax) ax2.set_ylabel('Humidity (%)') # Pressure plot ax = fig.add_subplot(313) ax.plot(dates.epoch2num(pressure[:, 0] - current.timezone), sealevel(pressure[:, 1], h) / 100, '-') ax.set_xlim(xlim) ax.set_ylabel('Pressure (mbar)') ax.set_xlabel('local time (%s)' % current.TZ) ax2 = ax.twinx() clim = pyplot.get(ax, 'ylim') ax2.set_ylim(clim[0] * 0.02954, clim[1] * 0.02954) datelabels(ax) ax.xaxis.set_major_locator(dates.HourLocator(interval=12)) ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M')) ax2.set_ylabel('P (inches Hg)') canvas = FigureCanvasAgg(fig) canvas.print_figure(os.path.join(args.outdir, 'plot.png'), dpi=80) canvas.print_figure(os.path.join(args.outdir, 'plot.pdf')) if args.upload: # upload static html file & images os.system('sitecopy -u weather') if args.show: # show the plot # doesn't work with FigureCanvasAgg #pyplot.show() # Linux (or X11 in OS X) os.system("display %s" % os.path.join(args.outdir, 'plot.png'))