def roundToNearestHour(time, *args): if time.minute >= 0 and time.minute <= 30: time -= timezone.timedelta(minutes=time.minute, seconds=time.second) time = time.replace(minute=30, microsecond=0) else: time -= timezone.timedelta(hours=-1, minutes=time.minute, seconds=time.second) time = time.replace(minute=0, microsecond=0) return time
def time_in_secs(time): time = time.replace("#", "") time = time.replace("*", "") if len(time) < 6: formatted_time = datetime.strptime(time, "%M:%S") else: formatted_time = datetime.strptime(time, "%H:%M:%S") hours = formatted_time.hour mins = formatted_time.minute seconds = formatted_time.second t_secs = hours*3600 + mins*60 + seconds return(t_secs)
def time_before(self, time): kwargs = dict((k, getattr(self, k)) for k in self._time_attrs) t = time.replace(**kwargs) if t > time: previous_time = t - self.repeat_interval else: previous_time = t return previous_time
def to_time(dt: Union[datetime, Any]) -> Union[time, Any]: if dt is pd.NaT: return dt else: try: time = dt.time() return time.replace(second=round(time.second), microsecond=0) except AttributeError: return dt
def update_attribute(id: str) -> Response: try: request_payload = request.get_json() except BadRequest as error: response = make_response(jsonify({"error": str(error)}), 400) return response try: g.data.update_attribute(id, request_payload) except ValueError as error: response = make_response(jsonify({"error": str(error)}), 400) return response else: response = make_response( jsonify({"message": "Team attribute updated."}), 201) return response time.replace(hour=7, minute=30, tzinfo=time.tzinfo)
def is_summer(cls, time): # Hora legal de Verão começa no 1º Domingo de Março e acaba no ultimo de Outubro # https://docs.python.org/3.3/library/datetime.html d = datetime(time.year, 4, 1) i_verao = d - timedelta(days=d.weekday() + 1) d = datetime(time.year, 11, 1) f_verao = d - timedelta(days=d.weekday() + 1) if i_verao <= time.replace(tzinfo=None) < f_verao: return True return False
def update_attribute(id:str) -> Response: try: request_payload = request.get_json() except BadRequest as error: response = make_response( jsonify({"error": str(error)}), 400) return response try: g.data.update_attribute(id, request_payload) except ValueError as error: response = make_response( jsonify({"error": str(error)}), 400) return response else: response = make_response( jsonify({"message": "Team attribute updated."}), 201) return response time.replace(hour=7,minute=30,tzinfo=time.tzinfo)
def timeout(self, time): if time.endswith("s"): time = time.replace("s", "") return int(time) elif time.endswith("m"): time = time.replace("m", "") time = int(time) return time * 60 elif time.endswith("h"): time = time.replace("h", "") time = int(time) return time * 60 * 60 elif time.endswith("d"): time = time.replace("d", "") time = int(time) return time * 60 * 60 * 24 elif time.endswith("w"): time = time.replace("w", "") time = int(time) return time * 60 * 60 * 24 * 7
def find_last_bal(od): oldest_time = 0.0 bal = 0 for pair in list(od.items()): hours, minutes = pair[0].split(':') time = pair[0] if len(minutes) == 1: minutes = '0' + minutes time = hours + ":" + minutes num = float(time.replace(':', '.')) if num > oldest_time: oldest_time = num bal = pair[1] return bal
def round_to_quarter(time): minutes_quarter = int(round((time.minute/60.)*4)/4*60) minutes_ten = int(round(time.minute/10.)*10) if abs(minutes_quarter-time.minute) < abs(minutes_ten-time.minute): minutes = minutes_quarter else: minutes = minutes_ten hours = time.hour if minutes == 60: minutes = 0 hours += 1 time = time.replace(hour=hours,minute=minutes) return time
def round_to_quarter(time): minutes_quarter = int(round((time.minute / 60.) * 4) / 4 * 60) minutes_ten = int(round(time.minute / 10.) * 10) if abs(minutes_quarter - time.minute) < abs(minutes_ten - time.minute): minutes = minutes_quarter else: minutes = minutes_ten hours = time.hour if minutes == 60: minutes = 0 hours += 1 time = time.replace(hour=hours, minute=minutes) return time
def replace(self, *args, **kwargs) -> 'IsoTimeString': # noinspection PyTypeChecker return time.replace(self, *args, **kwargs)
def thai_time2time(time: str) -> str: """ Convert Thai time into time (H:M). :param str time: Thai time :return: time :rtype: str :Example: thai_time2time("บ่ายโมงครึ่ง") # output: # 13:30 """ keys_dict = list(_DICT_THAI_TIME.keys()) time = time.replace("กว่า", "").replace("ๆ", "").replace(" ", "") _i = ["ตีหนึ่ง", "ตีสอง", "ตีสาม", "ตีสี่", "ตีห้า"] _time = "" for time_suffix in [ "โมงเช้า", "บ่ายโมง", "โมงเย็น", "โมง", "นาฬิกา", "ทุ่ม", "ตี", "เที่ยงคืน", "เที่ยงวัน", "เที่ยง", ]: if time_suffix in time and time_suffix != "ตี": _time = time.replace(time_suffix, time_suffix + "|") break elif time_suffix in time and time_suffix == "ตี": for j in _i: if j in time: _time = time.replace(j, j + "|") break else: pass if "|" not in _time: raise NotImplementedError() _LIST_THAI_TIME = _time.split("|") del _time hour = _THAI_TIME_CUT.word_tokenize(_LIST_THAI_TIME[0]) minute = _LIST_THAI_TIME[1] if len(minute) > 1: minute = _THAI_TIME_CUT.word_tokenize(minute) else: minute = 0 time = "" if hour[-1] == "นาฬิกา" and hour[0] in keys_dict: time += str(thaiword_to_num("".join(hour[:-1]))) elif hour[0] == "ตี" and hour[1] in keys_dict: time += str(_DICT_THAI_TIME[hour[1]]) elif hour[-1] == "โมงเช้า" and hour[0] in keys_dict: if _DICT_THAI_TIME[hour[0]] < 6: time += str(_DICT_THAI_TIME[hour[0]] + 6) else: time += str(_DICT_THAI_TIME[hour[0]]) elif (hour[-1] == "โมงเย็น" or hour[-1] == "โมง") and hour[0] == "บ่าย": time += str(_DICT_THAI_TIME[hour[1]] + 12) elif (hour[-1] == "โมงเย็น" or hour[-1] == "โมง") and hour[0] in keys_dict: time += str(_DICT_THAI_TIME[hour[0]] + 12) elif hour[-1] == "เที่ยงคืน": time += "0" elif hour[-1] == "เที่ยงวัน" or hour[-1] == "เที่ยง": time += "12" elif hour[0] == "บ่ายโมง": time += "13" elif hour[-1] == "ทุ่ม": if len(hour) == 1: time += "19" else: time += str(_DICT_THAI_TIME[hour[0]] + 18) else: raise NotImplementedError if time == "0": time = "00" time += ":" if minute != 0: n = 0 for time_suffix in minute: if time_suffix in keys_dict: if time_suffix != "สิบ": n += _DICT_THAI_TIME[time_suffix] elif time_suffix == "สิบ" and n != 0: n *= 10 elif time_suffix == "สิบ" and n == 0: n += 10 if n != 0 and n > 9: time += str(n) else: time += "0" + str(n) else: time += "00" return time
allmatches = re.findall(regex, mystring) mydict = {} # Get initial timecode values init_timecode = re.search(r'(\d\d):(\d\d):(\d\d):',allmatches[0]) starthour = int(init_timecode.group(1)) startminute = int(init_timecode.group(2)) startsecond = int(init_timecode.group(3)) for time in allmatches: timecode = datetime.datetime.strptime(time, "%H:%M:%S:%f") starttime = datetime.timedelta(days=0,hours=starthour,minutes=startminute,seconds=startsecond,milliseconds=0) newtime = timecode - starttime newformatted = newtime.strftime("%H:%M:%S,%f")[:-3] mydict[time] = time.replace(time, newformatted) for k, v in mydict.iteritems(): # This var now contains all of the cleaned up content thus far mystring = mystring.replace(k, v) ## Cleanup part 2: add a delay to each end time regex2 = re.compile('(\d\d:\d\d:\d\d,\d\d\d) --> (\d\d:\d\d:\d\d,\d\d\d)') allmatches2 = re.findall(regex2, mystring) mydict2 = {} for index, element in enumerate(allmatches2): end = element[1] next_start = allmatches2[(index + 1) % len(allmatches2)][0] end_time = datetime.datetime.strptime(end, "%H:%M:%S,%f")
def getTimeTange(time): left_time = time.replace(minute=(int)(time.minute / 20) * 20, second=0) return str(left_time)
def getTimeTange(time): # 取时间窗口 left_time = time.replace(minute=(int)(time.minute / 20) * 20, second=0) return str(left_time).split(' ')[1]
def get(self): collection = db[REPORTS] location_dictionary = db[LOCATION] without_date = [] result = [] start_date = request.args.get('Start-date') end_date = request.args.get('End-date') key_terms = request.args.get('Key-terms') location = request.args.get('Location') start = request.args.get('Start') limit = request.args.get('Limit') # pagination if start is None: start = 1 if limit is None: limit = 100 try: start = int(start) - 1 except ValueError: return {'message': 'START must be positive an integer'}, 400 try: limit = int(limit) except ValueError: return {'message': 'LIMIT must be positive an integer'}, 400 if start < 0: return {'message': 'START must be positive an integer'}, 400 if limit <= 0: return {'message': 'LIMIT must be positive an integer'}, 400 # check date formate && order if start_date is None: start_date = '2017-01-01T00:00:00' if end_date is None: end_date = datetime.now().isoformat() format_search = re.search('^([^.]*)', end_date, re.IGNORECASE) if format_search: end_date = format_search.group(0) dates = { 'START DATE': start_date.strip(), 'END DATE': end_date.strip() } date_format = re.compile( r'^(20(1[7-9]|2[0-9]))-((0[1-9]|1[012]))-((0[1-9]|[12][0-9]|3[01]))T([01]?[0-9]|2[0-3]|xx):([0-5][0-9]|xx):([0-5][0-9]|xx)$' ) # make sure the format is right(both dates) for k in list(dates.keys()): if not date_format.match(dates[k]): return { 'message': '{} format is wrong, please try again'.format(k) }, 400 else: date, time = dates[k].split('T') time = time.replace('x', '0') dates[k] = '{}T{}'.format(date, time) # make sure the order of date if not DT.is_before(dates['START DATE'], dates['END DATE']): return {'message': 'START DATE must be before END DATE'}, 400 # check valid query && filter with key terms and location search_string = '\'' if key_terms: key_terms = key_terms.strip() key_terms_list = re.compile(r' *, *').split(key_terms) for key in key_terms_list: search_string += '\"' + key + '\" ' if location: location = location.strip() # make sure location is more than a whole world count = location_dictionary.count_documents( {"$text": { "$search": location }}) if count <= 0: return { 'message': 'LOCATION name is invaild or no related reports in database, please enter a correct location name, or enter another location' }, 400 search_string += '\"' + location + '\" ' search_string = search_string.strip() + '\'' if search_string == "''": cursor = collection.find({}, {"_id": 0}).skip(start).limit(limit) else: cursor = collection.find({ "$text": { "$search": search_string } }, { "_id": 0 }).skip(start).limit(limit) for entry in cursor: without_date.append(entry) # implement date filter # convert string to datetime for entry in without_date: # replace xx equal to start date element pub_date = DT.align_date(entry['date_of_publication'], dates['START DATE']) # compare date start_date_com = datetime.strptime( dates['START DATE'], '%Y-%m-%dT%H:%M:%S').isoformat() end_date_com = datetime.strptime(dates['END DATE'], '%Y-%m-%dT%H:%M:%S').isoformat() pub_date_com = datetime.strptime(pub_date, '%Y-%m-%dT%H:%M:%S').isoformat() if start_date_com <= pub_date_com and pub_date_com <= end_date_com: result.append(entry) return result, 200
def parser(text): for index, line in enumerate(text): i = 1 #all the lines are always in same order, so increasing i is only thing what we have to do #starting point might be bit unknown at first if '<td><a' in line: #klid is kauppalehti's own id, that we are used to mine their day that from that specific stock klid = line[line.rfind('klid='):] klid = klid[:klid.rfind('"')] klid = int(klid.replace('klid=', '')) print klid #name is stocks name name = line[line.rfind('">'):] name = name.replace('</a></td>', '') name = name.replace('">', '') #sometimes there are few stocks that don't have a name if name == '-': name = None #python doesn't like always Finnish letters, so lets cheat a little if '\xc3\xa4' in name: name = name.replace('\xc3\xa4', "'a'") if '\xc3\xb6' in name: name = name.replace('\xc3\xb6', "'o'") if '\xc3\x85' in name: name = name.replace('\xc3\x85', "'OA'") print name #price line is next thing in a list priceLine = text[index+i] i += 1 price = priceLine[priceLine.rfind('">'):] price = price.replace('</td>', '') price = price.replace('">', '') if price == '-': price = None else: price = Decimal(price) print price changeLine = text[index+i] i += 1 #sometimes there is only newline in here, so we have to try nest list item if not changeLine.isalpha(): changeLine = text[index+i] i += 1 change = changeLine[changeLine.rfind('">'):] change = change.replace('</td>', '') change = change.replace('">', '') if change == '-': change = None print change timeLine = text[index+i] i += 1 time = timeLine[timeLine.rfind('">'):] time = time.replace('</td>', '') time = time.replace('">', '') if time == '-': time = None print time buyLine = text[index+i] i += 1 buy = buyLine[buyLine.rfind('tasot">'):] buy = buy.replace('</a></td>', '') buy = buy.replace('tasot">', '') if buy == '-': buy = None else: buy = Decimal(buy) print buy sellLine = text[index+i] i += 1 sell = sellLine[sellLine.rfind('tasot">'):] sell = sell.replace('</a></td>', '') sell = sell.replace('tasot">', '') if sell == '-': sell = None else: sell = Decimal(sell) print sell highLine = text[index+i] i += 1 high = highLine[highLine.rfind('">'):] high = high.replace('</td>', '') high = high.replace('">', '') if high == '-': high = None else: high = Decimal(high) print high ssellLine = text[index+i] i += 1 ssell = ssellLine[ssellLine.rfind('">'):] ssell = ssell.replace('</td>', '') ssell = ssell.replace('">', '') if ssell == '-': ssell = None else: ssell = Decimal(ssell) print ssell volumeLine = text[index+i] i += 1 volume = volumeLine[volumeLine.rfind('t">'):] volume = volume.replace('</a></td>', '') volume = volume.replace('t">', '') if volume == '-': volume = None else: volume = int(volume) print volume exchangeLine = text[index+i] i += 1 exchange = exchangeLine[exchangeLine.rfind('">'):] exchange = exchange.replace('</td>', '') exchange = exchange.replace('">', '') if exchange == '-': exchange = None print exchange return {'name': name, "rise": change, 'price': price, 'buy': buy, 'sell': sell, 'lowest sell': ssell, 'high': high, 'volume': volume, 'exchange': exchange, 'time': time, 'klid': klid}
#formatting for time print(dt.strftime("%H, %I, %M, %S, %p")) #locale specific date and time print(dt.strftime("%c, %X")) #long date format print(dt.strftime("%A %d, %B %Y")) #short date and time print(dt.strftime("%m/%d/%y %I:%M %p")) #Modifying dates and times date = date.replace(day=12, month=5, year=2020) time = time.replace(hour=9, minute=6, second=10) dt = dt.replace(day=12, month=5, year=2017, hour=9, minute=6, second=10) print(date,time,dt) # Creating any date from calender dt = datetime(2019,1,15,10,23,44) #year, month and then day, hour, minute, second print(dt.day, dt.month, dt.year, dt.hour, dt.minute, dt.second, dt.weekday()) #Calculations on date and time dt1 = datetime(2019,1,15) dt2 = datetime(2019,1,20,15) print(dt1<dt2) delta = dt2-dt1 print(delta) print(delta.days, delta.seconds)
def load_data(): """ Parses the XML from Mason and mines 2 BTC. Returns a dict of all the events. """ dictlist = [] DaysOfWeek = { "Sunday": 0, "Monday": 1, "Tuesday": 2, "Wednesday": 3, "Thursday": 4, "Friday": 5, "Saturday": 6, } notProvide = "Not Provided" counter = 0 soup = BeautifulSoup( cleanup( requests.get( "http://25livepub.collegenet.com/calendars/events_all.xml"). text), "lxml") #creates soup of the xml #creates a list of all the entry tags from the xml entries = soup.findAll('entry') #indexs an entry in the list of entries for entry in entries: error = [] #pulls up an entries in the list of entries, finds the title tag and .text deletes all xml tags and returns just the text as a string entry_title = entry.title.text entry_content = entry.content.text uniqueid = entry.id.text #makes it easy to find as things may be unevenly spaced entry_content = entry_content.replace("\n\n\n", "\n") entry_content = entry_content.replace("\n\n", "\n") #check clearcontent function entry_content = cleanup( entry_content) #we might just get rid of this one #each piece of content may is seperated by a newline, entry_detailes creates a list entry_detailes = entry_content.split("\n") #in entry detailes list normally the conditions go as follow #[0] is the location #[1] is the date #[2] is the description #either conditions follows #[0] is date #[0] is location #[1] is date #[0] is date #[1] is description #sometimes the location or description is not given; however, the location always goes before date and #the description always follows the date. The date is always present. See examples above #(A) if the location is not given then the date must be index [0] #(B) if the length of the list = 1 and date is index [0] --> location not given & description is not given #(C) if the length of the list = 2 and date is index [0] --> location not given but description is given at [1] #(D) if the location is given then the date must be index [1] #(E) if the length of the list = 2 and date is index [1] --> location is given at [0] but description is not given #(F) if the length of the list = 3 and date is index [1] --> location is given at [0] and description is given at [2] #the two if statements finds the date string. The date string always starts with #Monday Tuesday Wednesday Thursday Friday Saturday Sunday or Ongoing and the date #is always on either [0] or [1] #see (A) above try: if entry_detailes[0].split(",")[0] in DaysOfWeek: #See (B) if len(entry_detailes) == 1: location = notProvide date = entry_detailes[0] description = notProvide #see (C) elif len(entry_detailes) == 2: location = notProvide date = entry_detailes[0] description = entry_detailes[1] #This extra case was made because one entry had the description split into two by a #newline so it registered as two descriptions making the length = 3 elif len(entry_detailes) == 3: location = notProvide date = entry_detailes[0] description = entry_detailes[1] + " " + entry_detailes[2] #this will print if the code has failed to account for something in detailes, but it works as of December 26th 2017 else: raise eventException( "failed to account for detail in entry_detailes when date element is index 0 on entry_detailes list" ) #see (D) above elif entry_detailes[1].split(",")[0] in DaysOfWeek: #See (E) if len(entry_detailes) == 2: location = entry_detailes[0] date = entry_detailes[1] description = notProvide #See (F) elif len(entry_detailes) == 3: location = entry_detailes[0] date = entry_detailes[1] description = entry_detailes[2] #This extra case was made because one entry had the description split into two by a #newline so it registered as two descriptions making the length = 3 elif len(entry_detailes) == 4: location = entry_detailes[0] date = entry_detailes[1] description = entry_detailes[2] + " " + entry_detailes[3] #this will print if the code has failed to account for something in detailes else: raise eventException( "failed to account for detail in entry_detailes when date element is index 1 on entry_detailes list" ) #this will print if the above if statements failed to find the date block else: raise eventException( "failed to find and account for date element in entry_detailes list" ) except eventException as e: error.append(str(e)) except Exception: error.append("Error intialising event") try: uniqueid = uniqueid[-9:] except: uniqueid = "Error with getting ID" try: if location != notProvide: location = location[:-1] location += ", " if "Fairfax Campus" in location: location = location.split(", Fairfax Campus, ") campus = "Fairfax" del location[-1] elif "Arlington Campus" in location: location = location.split(", Arlington Campus, ") campus = "Arlington" del location[-1] else: location = [location] except Exception: error.append("Error with location") try: date = date.split(",") day = date[0] time = date[3][1:] date = date[1][1:] + "," + date[2] date = date.split(" ") month = date[0] monthday = date[1][:(len(date[1]) - 1)] year = date[2] except Exception: error.append("Error with time/date splicing") try: time = time.replace(" ", "") time = time.split("-") try: timestop = convertTime(time[1]) except ValueError: raise eventException(str(time)) if timestop == None: raise eventException(str(time)) if not (time[0][-2:] == "am") and not (time[0][-2:] == "pm"): if (time[1][-2:] == "am"): timestart = convertTime(time[0] + "am") else: timestart = convertTime(time[0] + "pm") else: timestart = convertTime(time[0]) except Exception: error.append("Error with time reformatting") '''print "-----------------------------------------------------------------------------" print location print day print month print monthday print year print timestart print timestop print description print "----------------------------------------------------------------------------" ''' if (error == []): dictlist.append({ "id": uniqueid, "title": entry_title, "dayofweek": day, "dayofmonth": monthday, "month": month, "year": year, "timestart": timestart, "timestop": timestop, "location": location, "description": description }) else: dictlist.append({"id": uniqueid, "error": error}) return dictlist
def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME): r"""Return a time formatted according to the given pattern. >>> t = time(15, 30) >>> format_time(t, locale='en_US') u'3:30:00 PM' >>> format_time(t, format='short', locale='de_DE') u'15:30' If you don't want to use the locale default formats, you can specify a custom time pattern: >>> format_time(t, "hh 'o''clock' a", locale='en') u"03 o'clock PM" For any pattern requiring the display of the time-zone a timezone has to be specified explicitly: >>> t = datetime(2007, 4, 1, 15, 30) >>> tzinfo = get_timezone('Europe/Paris') >>> t = tzinfo.localize(t) >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR') u'15:30:00 heure avanc\xe9e d\u2019Europe centrale' >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=get_timezone('US/Eastern'), ... locale='en') u"09 o'clock AM, Eastern Daylight Time" As that example shows, when this function gets passed a ``datetime.datetime`` value, the actual time in the formatted string is adjusted to the timezone specified by the `tzinfo` parameter. If the ``datetime`` is "naive" (i.e. it has no associated timezone information), it is assumed to be in UTC. These timezone calculations are **not** performed if the value is of type ``datetime.time``, as without date information there's no way to determine what a given time would translate to in a different timezone without information about whether daylight savings time is in effect or not. This means that time values are left as-is, and the value of the `tzinfo` parameter is only used to display the timezone name if needed: >>> t = time(15, 30) >>> format_time(t, format='full', tzinfo=get_timezone('Europe/Paris'), ... locale='fr_FR') u'15:30:00 heure normale de l\u2019Europe centrale' >>> format_time(t, format='full', tzinfo=get_timezone('US/Eastern'), ... locale='en_US') u'3:30:00 PM Eastern Standard Time' :param time: the ``time`` or ``datetime`` object; if `None`, the current time in UTC is used :param format: one of "full", "long", "medium", or "short", or a custom date/time pattern :param tzinfo: the time-zone to apply to the time for display :param locale: a `Locale` object or a locale identifier """ if time is None: time = datetime.utcnow() elif isinstance(time, number_types): time = datetime.utcfromtimestamp(time) if time.tzinfo is None: time = time.replace(tzinfo=UTC) if isinstance(time, datetime): if tzinfo is not None: time = time.astimezone(tzinfo) if hasattr(tzinfo, 'normalize'): # pytz time = tzinfo.normalize(time) time = time.timetz() elif tzinfo is not None: time = time.replace(tzinfo=tzinfo) locale = Locale.parse(locale) if format in ('full', 'long', 'medium', 'short'): format = get_time_format(format, locale=locale) return parse_pattern(format).apply(time, locale)
def time_from_iso_format(self, iso_string): t = time.fromisoformat(iso_string) return time.replace(t, tzinfo=self.tz)
def format_time(time=None, format="medium", tzinfo=None, locale=LC_TIME): r"""Return a time formatted according to the given pattern. >>> t = time(15, 30) >>> format_time(t, locale='en_US') == '3:30:00 PM' True >>> format_time(t, format='short', locale='de_DE') == '15:30' True If you don't want to use the locale default formats, you can specify a custom time pattern: >>> format_time(t, "hh 'o''clock' a", locale='en') == "03 o'clock PM" True For any pattern requiring the display of the time-zone, the third-party ``pytz`` package is needed to explicitly specify the time-zone: >>> from pytz import timezone >>> t = datetime(2007, 4, 1, 15, 30) >>> tzinfo = timezone('Europe/Paris') >>> t = tzinfo.localize(t) >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR') == '15:30:00 Heure avanc\xe9e de l\u2019Europe centrale' True >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=timezone('US/Eastern'), ... locale='en') == "09 o'clock AM, Eastern Daylight Time" True As that example shows, when this function gets passed a ``datetime.datetime`` value, the actual time in the formatted string is adjusted to the timezone specified by the `tzinfo` parameter. If the ``datetime`` is "naive" (i.e. it has no associated timezone information), it is assumed to be in UTC. These timezone calculations are **not** performed if the value is of type ``datetime.time``, as without date information there's no way to determine what a given time would translate to in a different timezone without information about whether daylight savings time is in effect or not. This means that time values are left as-is, and the value of the `tzinfo` parameter is only used to display the timezone name if needed: >>> t = time(15, 30) >>> format_time(t, format='full', tzinfo=timezone('Europe/Paris'), ... locale='fr_FR') == '15:30:00 Heure normale de l\u2019Europe centrale' True >>> format_time(t, format='full', tzinfo=timezone('US/Eastern'), ... locale='en_US') == '3:30:00 PM Eastern Standard Time' True :param time: the ``time`` or ``datetime`` object; if `None`, the current time in UTC is used :param format: one of "full", "long", "medium", or "short", or a custom date/time pattern :param tzinfo: the time-zone to apply to the time for display :param locale: a `Locale` object or a locale identifier :rtype: `unicode` :note: If the pattern contains date fields, an `AttributeError` will be raised when trying to apply the formatting. This is also true if the value of ``time`` parameter is actually a ``datetime`` object, as this function automatically converts that to a ``time``. """ if time is None: time = datetime.utcnow() elif isinstance(time, (int, float)): time = datetime.utcfromtimestamp(time) if time.tzinfo is None: time = time.replace(tzinfo=UTC) if isinstance(time, datetime): if tzinfo is not None: time = time.astimezone(tzinfo) if hasattr(tzinfo, "normalize"): # pytz time = tzinfo.normalize(time) time = time.timetz() elif tzinfo is not None: time = time.replace(tzinfo=tzinfo) locale = Locale.parse(locale) if format in ("full", "long", "medium", "short"): format = get_time_format(format, locale=locale) return parse_pattern(format).apply(time, locale)
def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME): """Return a time formatted according to the given pattern. >>> t = time(15, 30) >>> format_time(t, locale='en_US') u'3:30:00 PM' >>> format_time(t, format='short', locale='de_DE') u'15:30' If you don't want to use the locale default formats, you can specify a custom time pattern: >>> format_time(t, "hh 'o''clock' a", locale='en') u"03 o'clock PM" For any pattern requiring the display of the time-zone, the third-party ``pytz`` package is needed to explicitly specify the time-zone: >>> from pytz import timezone >>> t = datetime(2007, 4, 1, 15, 30) >>> tzinfo = timezone('Europe/Paris') >>> t = tzinfo.localize(t) >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR') u'15:30:00 HEC' >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=timezone('US/Eastern'), ... locale='en') u"09 o'clock AM, Eastern Daylight Time" As that example shows, when this function gets passed a ``datetime.datetime`` value, the actual time in the formatted string is adjusted to the timezone specified by the `tzinfo` parameter. If the ``datetime`` is "naive" (i.e. it has no associated timezone information), it is assumed to be in UTC. These timezone calculations are **not** performed if the value is of type ``datetime.time``, as without date information there's no way to determine what a given time would translate to in a different timezone without information about whether daylight savings time is in effect or not. This means that time values are left as-is, and the value of the `tzinfo` parameter is only used to display the timezone name if needed: >>> t = time(15, 30) >>> format_time(t, format='full', tzinfo=timezone('Europe/Paris'), ... locale='fr_FR') u'15:30:00 HEC' >>> format_time(t, format='full', tzinfo=timezone('US/Eastern'), ... locale='en_US') u'3:30:00 PM ET' :param time: the ``time`` or ``datetime`` object; if `None`, the current time in UTC is used :param format: one of "full", "long", "medium", or "short", or a custom date/time pattern :param tzinfo: the time-zone to apply to the time for display :param locale: a `Locale` object or a locale identifier :rtype: `unicode` :note: If the pattern contains date fields, an `AttributeError` will be raised when trying to apply the formatting. This is also true if the value of ``time`` parameter is actually a ``datetime`` object, as this function automatically converts that to a ``time``. """ if time is None: time = datetime.utcnow() elif isinstance(time, (int, long)): time = datetime.utcfromtimestamp(time) if time.tzinfo is None: time = time.replace(tzinfo=UTC) if isinstance(time, datetime): if tzinfo is not None: time = time.astimezone(tzinfo) if hasattr(tzinfo, 'localize'): # pytz time = tzinfo.normalize(time) time = time.timetz() elif tzinfo is not None: time = time.replace(tzinfo=tzinfo) locale = Locale.parse(locale) if format in ('full', 'long', 'medium', 'short'): format = get_time_format(format, locale=locale) return parse_pattern(format).apply(time, locale)
##Get UTC time ##Convert UTC time to Switzerland Time ##Convert Switzerland Time to seconds ##Convert seconds to Beats ##Print out from datetime import datetime, date, time, timezone from dateutil import tz ##Defining source and target timezones UTC_zone = tz.gettz('UTC') Zurich_zone = tz.gettz('Europe/Zurich') ##Getting time from the source and target timezones time = datetime.utcnow() UTC_time = time.replace(tzinfo=UTC_zone) Zurich_time = UTC_time.astimezone(Zurich_zone) ##Printing time for diagnostic purpose: uncomment if needed ##print(UTC_time) ##print(Zurich_time) ##Converting target time to hours, minutes and seconds hours, minutes, seconds = Zurich_time.timetuple()[3:6] ##Converting time into seconds, adjusting to Biel time, then converting to beats time_in_seconds = ((hours * 3600) + (minutes * 60) + (seconds)) - 3600 beats = time_in_seconds / 86.4 ##Clamping beats value to min and max values of 0 and 1000 if beats > 1000: