def test(self): cursor = self.mem_db['connection'].cursor() sql = ' '.join(["SELECT *", "FROM properties"]) cursor.execute(sql) for (uuid, uuid_obj, key, value, v_type) in cursor: print(uuid, uuid_obj, key, value, v_type) sql = ' '.join(["SELECT *", "FROM objects"]) cursor.execute(sql) for (uuid_obj, o_type, class_name, dt_create) in cursor: t = datetime.fromtimestamp(dt_create, timezone.utc) t1 = datetime.astimezone(t) print(uuid_obj, o_type, dt_create, t, t1) sql = ' '.join(["SELECT *", "FROM relations"]) cursor.execute(sql) for (uuid_src, uuid_dst, rel_type, dt_create) in cursor: t = datetime.fromtimestamp(dt_create, timezone.utc) t1 = datetime.astimezone(t) print(uuid_src, uuid_dst, rel_type, dt_create, t, t1) sql = ' '.join(["SELECT *", "FROM objects, relations, properties", "WHERE relations.rel_type = :rel_type"]) cursor.execute(sql, {"rel_type":"str"}) res = cursor.fetchall() for row in res: print(row)
def Hours_of_day_X_dt_aware(date_input_aware): # datetime # set 0100 o'clock for give aware date dt_local_01 = date_input_aware # retrieve tzinfo from give aware date dt_local_01_zone = dt_local_01.tzinfo # translate to astimezone in UTC dt_utc_01 = datetime.astimezone(dt_local_01, pytz.utc) # time in utc with day plus 1 dt_utc_02 = dt_utc_01 + timedelta(days=1) dt_local_02 = datetime.astimezone(dt_utc_02, dt_local_01_zone) # 1.3.1 calculate utc office dt_utc_local_offset_01 = datetime.utcoffset(dt_local_01) dt_utc_local_offset_02 = datetime.utcoffset(dt_local_02) # 1.4 final step to calculate number of hours of that day to be tested number_hours = 24 - dt_utc_local_offset_02.seconds / 3600 + dt_utc_local_offset_01.seconds / 3600 # print outputs def print_hours_of_that_day(): print('AWARE - def - Number of hours of that day:', number_hours) print('') if __name__ == '__main__': print_hours_of_that_day() return number_hours
def _increment_occurence(self,datetime): datetime = self.timezone.normalize(datetime.astimezone(self.timezone)) datetime = datetime + self.increment_by() datetime = pytz.utc.normalize(datetime.astimezone(pytz.utc)) #Don't trust relative delta to keep the same times in every case #We want to ensure the times are kept across DST for example return self._set_start_time(datetime)
def get_events(self, start, end=None): event_list = [] # Date range should be datetime objects ... if isinstance(start, date): zero_time = time(0, 0, 0, 0, tzinfo=pytz.UTC) start = datetime.combine(start, zero_time) if isinstance(end, date): max_time = time(23, 59, 59, 999999, tzinfo=pytz.UTC) end = datetime.combine(end, max_time) # ... and those datetime objects should be timezone aware if start.tzinfo is None: start = datetime.astimezone(pytz.UTC) if end.tzinfo is None: end = datetime.astimezone(pytz.UTC) calendar_url = self.get_caldav_url() client = caldav.DAVClient(calendar_url) calendar = caldav.Calendar(client, calendar_url) for vcal in calendar.date_search(start, end): for comp in vcal.instance.components(): # RecurringComponent might be misleading, but vobject # returns all events as RecurringComponent objects if isinstance(comp, RecurringComponent): self._handle_event_component(start, end, comp, event_list) return event_list
def _set_start_time(self,datetime): #This may be required to handle DST datetime = self.timezone.normalize(datetime.astimezone(self.timezone)) starting_time = self.timezone.normalize(self.starting_time.astimezone(self.timezone)) datetime = datetime.replace( hour=starting_time.hour, minute=starting_time.minute, second=starting_time.second ) return pytz.utc.normalize(datetime.astimezone(pytz.utc))
def __init__(self, *args, **kwargs): super(EntrevistaDetailEmpresaForm, self).__init__(*args, **kwargs) if self.instance.status == 'REA': if self.instance.pasantia_aceptada == True or self.instance.pasantia_aceptada == False: self.fields['pasantia_aceptada'].disabled = True else: self.fields.pop('pasantia_aceptada') if not self.instance.status in ['NOA'] or datetime.astimezone( self.instance.fecha - td(days=1)) < datetime.astimezone( datetime.now()): self.fields['fecha'].disabled = True self.fields['lugar'].disabled = True self.fields['comentarios_comision_pps'].disabled = True self.fields['fecha'].input_formats = ['%Y/%m/%d - %H:%M hs.']
def get_time_boundaries(self, year, month): endyear = year + month // 12 endmonth = (month % 12) + 1 start = datetime(year, month, 1, 0, 0, 0) end = datetime(endyear, endmonth, 1, 0, 0, 0) bound = { "start": datetime.astimezone(start, self._tz).strftime("%Y-%m-%dT%H:%M:%S.%fZ"), "end": datetime.astimezone(end, self._tz).strftime("%Y-%m-%dT%H:%M:%S.%fZ") } logger.debug(f"time boundaries: {bound}") return bound
def index(): form1 = TodoForm() if form1.validate_on_submit(): day = form1.day.data month = form1.month.data year = form1.year.data hour = form1.hour.data minute = form1.minute.data a_p = form1.a_p.data date_str = year + '-' + month + '-' + day + '-' \ + hour + '-' + minute + '-' + a_p datetime_obj = datetime.strptime(date_str, '%Y-%b-%d-%I-%M-%p') datetime_obj = datetime.astimezone(datetime_obj, pytz.UTC) sanitized = html.escape(form1.todo.data) todo = Todo(body=sanitized, author=current_user, due_date=datetime_obj) db.session.add(todo) db.session.commit() return redirect(url_for('main.index')) page = request.args.get('page', 1, type=int) todos = current_user.all_todos().paginate( page, current_app.config['TODOS_PER_PAGE'], False) next_url = url_for('main.index', page=todos.next_num) \ if todos.has_next else None prev_url = url_for('main.index', page=todos.prev_num) \ if todos.has_prev else None return render_template('index.html', title=_('Home'), form=form1, todos=todos.items, next_url=next_url, prev_url=prev_url)
def check_and_send_not_paid_user_notification(batch_id, config, logger): last_change_dt = datetime.utcnow() eta = datetime.utcnow() eta = eta.replace(tzinfo=pytz.utc) timezone_name = BatchManager.get_batch_timezone(batch_id) or "Europe/Moscow" eta = datetime.astimezone(eta, pytz.timezone(timezone_name)) eta += timedelta(seconds=config['NOT_PAID_BATCH_NOTIFY_TIMEOUT_SECONDS']) try: not_paid_batch_notify_desired_time = config['NOT_PAID_BATCH_NOTIFY_DESIRED_TIME'] if not_paid_batch_notify_desired_time: desired_time = datetime.strptime(not_paid_batch_notify_desired_time, "%H:%M") dt = eta.replace(hour=desired_time.hour, minute=desired_time.minute) if dt < eta: dt += timedelta(days=1) eta = dt eta = eta.astimezone(pytz.utc).replace(tzinfo=None) except Exception: logger.exception(u"Failed to calculate correct send time") from fw.async_tasks import not_paid_check_send not_paid_check_send.not_paid_check_and_send.apply_async(kwargs={ 'batch_id': str(batch_id), 'last_change_dt_str': last_change_dt.strftime("%Y-%m-%dT%H:%M:%S") }, eta=eta)
def save(self) -> "Model": """Insert or update data if self.id is set. Return the save object (self) """ now = datetime.astimezone(datetime.now()) if self.id: self.updated_on = now data = self.todict() res = ( self.__r.table(self.tablename) .get(self.id) .update(data) .run(self.__conn) ) if res.get("errors") != 0: msg = f"An error occured on create in {self.tablename} entry: {res['first_error']}" raise errors.ReqlError(msg) self.on_modified() else: self.created_on = now data = self.todict() del data["id"] res = self.__r.table(self.tablename).insert(data).run(self.__conn) if res.get("errors") != 0: msg = f"An error occured on insert in {self.tablename} entry: {res['first_error']}" raise errors.ReqlError(msg) self.id = res.get("generated_keys")[0] self.on_created() return self
def generate_datetime3(datetime: datetime) -> str: """""" utc_tz = pytz.utc.normalize(datetime.astimezone(pytz.utc)) utc_tz = utc_tz.replace(tzinfo=None) dt = utc_tz.isoformat() dt = dt.replace('T', ' ') return dt
def admission(self, registrations): registration_id = registrations[0] Bed = self.env['gnuhealth.hospital.bed'] Company = self.env['company.company'] timezone = None company_id = Transaction().context.get('company') if company_id: company = Company(company_id) if company.timezone: timezone = pytz.timezone(company.timezone) dt = datetime.today() dt_local = datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone) if (registration_id.hospitalization_date.date() != dt_local.date()): self.raise_user_error("The Admission date must be today") else: self.write(registrations, {'state': 'hospitalized'}) Bed.write([registration_id.bed], {'state': 'occupied'}) else: self.raise_user_error('need_timezone')
def datetime_to_HTTP_date(date_and_time): """ Returns a HTTP-date as defined in rfc7234 section 5.3 for a datetime object""" return datetime.astimezone(date_and_time).strftime( "%a, %d %b %Y %H:%M:%S %Z")
def advance_till(self, datetime): assert (datetime.tzinfo is not None) datetime = datetime.astimezone(self.tz) while (self.next().datetime < datetime): self.advance() return self.next()
def datetime_utc_mexico(): from datetime import datetime import pytz mexico = pytz.timezone('America/Mexico_City') date = datetime.now(pytz.utc) return datetime.astimezone(date, mexico)
def user_time(self, dt=None): if not dt: dt = datetime.utcnow() return datetime.astimezone( dt.replace(tzinfo=pytz.utc), pytz.timezone(self.current_user['timezone']), )
def get_context(cls, records, data): Company = Pool().get('company.company') company_id = Transaction().context.get('company') company = Company(company_id) context = Transaction().context report_context = super(InvoiceReport, cls).get_context(records, data) voucher = records[0] if voucher.amount: d = str(voucher.amount) decimales = d[-2:] if decimales[0] == '.': decimales = decimales[1] + '0' if company.timezone: timezone = pytz.timezone(company.timezone) dt = datetime.now() hora = datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone) report_context['company'] = company report_context['decimales'] = decimales report_context['hora'] = hora.strftime('%H:%M:%S') report_context['fecha'] = hora.strftime('%d/%m/%Y') report_context['transfer'] = 'false' new_objs = [] for obj in objects: if obj.amount_to_pay and conversor and not obj.amount_to_pay_words: obj.amount_to_pay_words = obj.get_amount2words( obj.amount_to_pay) new_objs.append(obj) return report_context
def _get_fecha(cls, Sale, sale): if sale.company.timezone: timezone = pytz.timezone(sale.company.timezone) dt = sale.create_date fecha = datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone) return fecha
def parse(cls, report, objects, data, localcontext): pool = Pool() User = pool.get('res.user') user = User(Transaction().user) Date = pool.get('ir.date') Company = pool.get('company.company') Sale = pool.get('sale.sale') fecha = data['date'] total_ventas = Decimal(0.0) total_iva = Decimal(0.0) subtotal_total = Decimal(0.0) subtotal14 = Decimal(0.0) subtotal0 = Decimal(0.0) subtotal12 = Decimal(0.0) total_recibido = Decimal(0.0) total_por_cobrar = Decimal(0.0) company = Company(data['company']) sales = Sale.search([('sale_date', '=', fecha), ('state', '!=', 'draft')]) if sales: for s in sales: if s.total_amount > Decimal(0.0): total_ventas += s.total_amount total_iva += s.tax_amount subtotal_total += s.untaxed_amount total_recibido += s.paid_amount total_por_cobrar += s.residual_amount for line in s.lines: if line.product.taxes_category == True: impuesto = line.product.category.taxes else: impuesto = line.product.taxes if impuesto == 'iva0' or impuesto == 'no_iva': subtotal0 = subtotal0 + (line.amount) if impuesto == 'iva14': subtotal14 = subtotal14 + (line.amount) if impuesto == 'iva12': subtotal12 = subtotal12 + (line.amount) if company.timezone: timezone = pytz.timezone(company.timezone) dt = datetime.now() hora = datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone) localcontext['company'] = company localcontext['fecha'] = fecha.strftime('%d/%m/%Y') localcontext['hora'] = hora.strftime('%H:%M:%S') localcontext['fecha_im'] = hora.strftime('%d/%m/%Y') localcontext['total_ventas'] = total_ventas localcontext['sales'] = sales localcontext['total_iva'] = total_iva localcontext['subtotal_total'] = subtotal_total localcontext['subtotal14'] = subtotal14 localcontext['subtotal0'] = subtotal0 return super(ReportSales, cls).parse(report, objects, data, localcontext)
def button_admission(self): self.ensure_one() Bed = self.env['medical.hospital.bed'] Company = self.env['res.company'] timezone = None company_id = self._context.get('company') if company_id: company = Company(company_id) if company.timezone: timezone = pytz.timezone(company.timezone) dt = datetime.today() dt_local = datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone) if (self.hospitalization_date.date() != dt_local.date()): raise UserError(_('The Admission date must be today.')) else: self.write({'state': 'hospitalized'}) self.bed.write({'state': 'occupied'}) else: raise UserError(_('You need to set up the company timezone.'))
def LoadInventory(): timezone = pytz.timezone('America/Guayaquil') dt = datetime.today() fecha = datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone) inventory = Inventory() location = Location.find([('type', '=', 'storage'), ('id', '=', 3)]) print "Location ", location inventory.location = location[0] inventory.date = fecha lost_found, = Location.find([('type', '=', 'lost_found')]) inventory.lost_found = lost_found products = csv.reader(open('inventario.csv', 'r')) inicio = 2 for i in range(inicio - 1): products.next() cont = 1 for index,row in enumerate(products): code = row[0] cantidad = int(row[1]) if cantidad < 1: cantidad = int(0) producto = Product.find([('code', '=', code)]) if producto: if producto[0].template.type == "service": pass else: print "Product ",cont, producto[0].code inventory.lines.new(product=producto[0], quantity=cantidad) cont = cont +1 inventory.save() print "Creado inventario", inventory
def to_utc(datetime): """Convert a datetime object to UTC and drop tzinfo. This is the opposite operation to :func:`to_user_timezone`. """ if datetime.tzinfo is None: datetime = get_timezone().localize(datetime) return datetime.astimezone(UTC).replace(tzinfo=None)
def user_time(user, dt=None): if not dt: dt = datetime.utcnow() return datetime.astimezone( dt.replace(tzinfo=pytz.utc), pytz.timezone(user.timezone), )
def __init__(self, datetime=None, source=None, rid=None, rtype=None, coin=None, amount=None, infee=None, exfee=None, balance=None, value=None, profit=None, cost=None): if (rtype is not None): RecordType.check_value(rtype) # raise ValueError if (coin is not None): CoinName.check_value(coin) # raise ValueError #def as_decimal(x): return x if type(x) in (type(None), Decimal) else Decimal(x) def as_decimal(x): return x if type(x) in ( type(None), Decimal) else None if x == '' else Decimal(x) self.datetime = datetime.astimezone(timezone.utc) self.source = normalize_source(source) self.rid = rid self.rtype = rtype self.coin = coin self.amount = as_decimal(amount) self.infee = as_decimal(infee) self.exfee = as_decimal(exfee) self.balance = as_decimal(balance) self.value = as_decimal(value) self.profit = as_decimal(value) self.cost = as_decimal(cost)
def format_datetime(datetime): if datetime is None: return '' tz = tzlocal() return defaultfilters.date(datetime.astimezone(tz), "SHORT_DATETIME_FORMAT")
def create_games(self): print('Games creation:') current_date = self.start_date quests = Quest.objects.all() while current_date < self.end_date: for i in range(self.games_count_per_day): timespan = datetime.astimezone( current_date + timezone.timedelta(hours=random.randrange(1, 23), minutes=random.randrange(1, 60), seconds=random.randrange(1, 60)), tz=pytz.utc) game = Game.objects.create( title='Game_' + str(i + 1), description=self.make_game_description( current_date, i + 1), genre=random.choices(self.genres)[0], timespan=timespan, duration=random.choices(self.game_durations)[0], quest=random.choices(quests)[0], level=random.choices(['1', '2', '3', '4', '5'])[0], price=random.randrange(100, 999), min_players_count=random.randrange(2, 4), max_players_count=6, cancel=False, ) Team.objects.create(game=game, ) print('.', end='', flush=True) current_date += timezone.timedelta(days=1) games = Game.objects.all() self.set_images(games, 'game_photos', 'fc_{}.jpg', 'photo') self.set_images(games, 'game_covers', 'game_{}.jpg', 'cover_image') print('\nGames creation: DONE')
def _extract_xml_locations(path: Path) -> Iterator[Res[Location]]: # the tags are sort of strange here, because they include the # input format (URL). cant use findall easily, have to loop through # and find substrings of the matching tags tr = etree.parse(str(path)) for el in tr.getroot(): # gpx element if el.tag.endswith("trk"): for trkseg in el: # trk for trkpt in trkseg: latlon_dict: Dict[str, str] = trkpt.attrib try: assert "lat" in latlon_dict assert "lon" in latlon_dict except AssertionError as ae: return ae for child in trkpt: # believe this is UTC, since gpx times start at 8AM and I'm in PST if child.tag.endswith("time"): yield Location( dt=datetime.astimezone( datetime.fromisoformat( child.text.rstrip("Z")), tz=timezone.utc, ), lat=float(latlon_dict["lat"]), lng=float(latlon_dict["lon"]), ) else: return RuntimeError("Could not find 'trk' element in GPX XML")
def cast_datetime_to_utc(datetime): """ If datetime has no tzinfo, assume it is UTC, otherwise convert the datetime to UTC. """ if datetime.tzinfo is None: return datetime.replace(tzinfo=timezone.utc) return datetime.astimezone(timezone.utc)
def astimezone(self, tzinfo): """Convert to local time in new timezone tz. The result is normalized across DST boundaries.""" dt = _datetime.astimezone(self, tzinfo) dt = tzinfo.normalize(dt) return datetime.__from_datetime_with_tz(dt)
def cast_datetime_to_naive(datetime): """ Removes timezone information, but converts non-UTC datetimes to UTC beforehand so that the returned datetime will be naive but will also be UTC. """ if datetime.tzinfo is not None: datetime = datetime.astimezone(timezone.utc) return datetime.replace(tzinfo=None)
def datetime_to_iso8601_utc(datetime): """ Accepts a datetime.datetime object with UTC timezone. Returns a string like: 2020-03-26T09:10:11Z """ isoformat = datetime.astimezone( timezone.utc).replace(tzinfo=None).isoformat() return f"{isoformat}Z"
def tz_to_utc(self, datetime): """Convert the provided datetime object from local to UTC. The datetime object is expected to have the timezone specified in the timezone attribute. """ utc = pytz.utc return datetime.astimezone(utc)
def astimezone(self,tz): """ Identical to datetime.astimezone() but returns an AstroTime. Performs leap-second adjustments if necessary. """ delta = self.__leapseconds(tz) - self.__leapseconds(self.tzinfo) return AstroTime(datetime=datetime.astimezone(self,tz),deltasecs=delta)
def utc_to_tz(self, datetime): """Convert the provided datetime object from UTC to local. The resulting localized datetime object will have the timezone specified in the timezone attribute. """ return self.timezone.normalize(datetime.astimezone(self.timezone))
def UTC_datetime2local(datetime, coords): """Convert TCX UTC's datetimes to local time""" datetime = pytz.utc.localize( datetime) #Garmin's TCX datetimes are always UTC, but only implicitly return datetime.astimezone( pytz.timezone(TimezoneFinder().timezone_at(lng=coords[0], lat=coords[1])))
def astimezone(self, tz): """ Identical to datetime.astimezone() but returns an AstroTime. Performs leap-second adjustments if necessary. """ delta = self.__leapseconds(tz) - self.__leapseconds(self.tzinfo) return AstroTime(datetime=datetime.astimezone(self, tz), deltasecs=delta)
def tzconv(self, datetime): '''Takes datetime object, sets timezone as Pacific Time and the convents timezone to Eastern Time. Necessary because Ekos export names incorporate time of download in Eastern Time. DST = Daylight Savings Time''' logger.info("Adjusting Timezones") datetime = timezone('UTC').localize(datetime) datetime = datetime.astimezone(timezone('US/Eastern')) return datetime
def to_user_timezone(tzinfo, datetime): """Convert a datetime object to the user's timezone. This automatically happens on all date formatting unless rebasing is disabled. If you need to convert a :class:`datetime.datetime` object at any time to the user's timezone (as returned by :func:`get_timezone` this function can be used). """ if datetime.tzinfo is None: datetime = datetime.replace(tzinfo=UTC) return tzinfo.normalize(datetime.astimezone(tzinfo))
def skeletonfmt(datetime=None, skeleton='yMEd', tz=None, locale=None): if tz is None: tz = tzlocal() if locale is None: locale = get_current_locale() datetime = datetime.astimezone(tz) return format_skeleton(skeleton, datetime, locale=locale)
def astimezone(self, tzinfo): """Convert to local time in new timezone tz. The result is normalized across DST boundaries.""" if hasattr(tzinfo, '_get_current_object'): tzinfo = tzinfo._get_current_object() dt = _datetime.astimezone(self, tzinfo) dt = tzinfo.normalize(dt) return datetime.__from_datetime_with_tz(dt)
def get_print_date(): Company = Pool().get('company.company') timezone = None company_id = Transaction().context.get('company') if company_id: company = Company(company_id) if company.timezone: timezone = pytz.timezone(company.timezone) dt = datetime.now() return datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone)
def to_utc(self, datetime): """Returns a datetime object converted to UTC and without tzinfo. :param datetime: A ``datetime`` object. :returns: A naive ``datetime`` object (no timezone), converted to UTC. """ if datetime.tzinfo is None: datetime = self.tzinfo.localize(datetime) return datetime.astimezone(pytz.UTC).replace(tzinfo=None)
def to_local_timezone(self, datetime): """Returns a datetime object converted to the local timezone. :param datetime: A ``datetime`` object. :returns: A ``datetime`` object normalized to a timezone. """ if datetime.tzinfo is None: datetime = datetime.replace(tzinfo=pytz.UTC) return self.tzinfo.normalize(datetime.astimezone(self.tzinfo))
def get_report_surgery_time(self, name): Company = Pool().get('company.company') timezone = None company_id = Transaction().context.get('company') if company_id: company = Company(company_id) if company.timezone: timezone = pytz.timezone(company.timezone) dt = self.surgery_date return datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone).time()
def makeAnswerField(zoneName): utcDate = datetime.utcnow() utcDate = utcDate.replace(tzinfo=pytz.utc) time = datetime.astimezone(utcDate, pytz.timezone(zoneName)) time = datetime.strftime(time,DayTimeProtocol.TIME_FORMAT) '''if not deltaTime: time = datetime.strftime(datetime.utcnow(),DayTimeProtocol.TIME_FORMAT) else: timeObject = datetime.utcnow() + timedelta(hours = deltaTime) time = datetime.strftime(timeObject,DayTimeProtocol.TIME_FORMAT) if len(zoneName) > DayTimeProtocol.BYTES_ANSWER_ZONE_NAME[2]: zoneName[:DayTimeProtocol.BYTES_ANSWER_ZONE_NAME[2]]''' return [zoneName.ljust(DayTimeProtocol.BYTES_ANSWER_ZONE_NAME[2]),time]
def to_utc(datetime): """Returns a datetime object converted to UTC and without tzinfo. This function derives from `Kay <http://code.google.com/p/kay-framework/>`_. :param datetime: A ``datetime`` object. :returns: A naive ``datetime`` object (no timezone), converted to UTC. """ if datetime.tzinfo is None: datetime = get_timezone().localize(datetime) return datetime.astimezone(pytz.UTC).replace(tzinfo=None)
def fix_tzinfo(self, datetime, tz=None): if tz is None and self.user: tz = self.user.get_timezone() # 1. Build the tzinfo object tzinfo = timezone(tz) if tz else local_tz # 2. Change datetime if datetime.tzinfo: datetime = datetime.astimezone(tzinfo) else: datetime = tzinfo.localize(datetime) return datetime
def calc_fixed_time_not_earlier(start_dt, desired_time_str, timeout_td, timezone_name): eta = copy(start_dt) eta = eta.replace(tzinfo=pytz.utc) eta = datetime.astimezone(eta, pytz.timezone(timezone_name)) eta += timeout_td if desired_time_str: desired_time = datetime.strptime(desired_time_str, "%H:%M") dt = eta.replace(hour=desired_time.hour, minute=desired_time.minute) if dt < eta: dt += timedelta(days=1) eta = dt eta = eta.astimezone(pytz.utc).replace(tzinfo=None) return eta
def to_local_timezone(datetime): """Returns a datetime object converted to the local timezone. This function derives from `Kay <http://code.google.com/p/kay-framework/>`_. :param datetime: A ``datetime`` object. :returns: A ``datetime`` object normalized to a timezone. """ tzinfo = get_timezone() if datetime.tzinfo is None: datetime = datetime.replace(tzinfo=pytz.UTC) return tzinfo.normalize(datetime.astimezone(tzinfo))
def format_datetime(datetime=None, format='medium', tzinfo=None, locale=LC_TIME): """Return a date formatted according to the given pattern. >>> dt = datetime(2007, 04, 01, 15, 30) >>> format_datetime(dt, locale='en_US') u'Apr 1, 2007 3:30:00 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 >>> format_datetime(dt, 'full', tzinfo=timezone('Europe/Paris'), ... locale='fr_FR') u'dimanche 1 avril 2007 17:30:00 HEC' >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz", ... tzinfo=timezone('US/Eastern'), locale='en') u'2007.04.01 AD at 11:30:00 EDT' :param datetime: the `datetime` object; if `None`, the current date and time is used :param format: one of "full", "long", "medium", or "short", or a custom date/time pattern :param tzinfo: the timezone to apply to the time for display :param locale: a `Locale` object or a locale identifier :rtype: `unicode` """ if datetime is None: datetime = datetime_.utcnow() elif isinstance(datetime, (int, long)): datetime = datetime_.utcfromtimestamp(datetime) elif isinstance(datetime, time): datetime = datetime_.combine(date.today(), datetime) if datetime.tzinfo is None: datetime = datetime.replace(tzinfo=UTC) if tzinfo is not None: datetime = datetime.astimezone(tzinfo) if hasattr(tzinfo, 'normalize'): # pytz datetime = tzinfo.normalize(datetime) locale = Locale.parse(locale) if format in ('full', 'long', 'medium', 'short'): return get_datetime_format(format, locale=locale) \ .replace('{0}', format_time(datetime, format, tzinfo=None, locale=locale)) \ .replace('{1}', format_date(datetime, format, locale=locale)) else: return parse_pattern(format).apply(datetime, locale)
def parse(cls, report, objects, data, localcontext): Company = Pool().get('company.company') timezone = None company_id = Transaction().context.get('company') if company_id: company = Company(company_id) if company.timezone: timezone = pytz.timezone(company.timezone) dt = datetime.now() localcontext['print_date'] = datetime.astimezone(dt.replace( tzinfo=pytz.utc), timezone) localcontext['print_time'] = localcontext['print_date'].time() return super(PatientEvaluationReport, cls).parse(report, objects, data, localcontext)
def onPrintLabelClicked(self, cr, uid, ids, context=None): print 'onPrintLabelClicked' datas = {'ids':ids} # Change localized date accordingly #print str(localDate) print str(ids) dateString = self.browse(cr, uid, ids, context=None)[0].date print 'creation date: ' + dateString utcDate = datetime.strptime(dateString, "%Y-%m-%d %H:%M:%S") utcDate = utcDate.replace(tzinfo=pytz.utc) local = datetime.astimezone(utcDate, pytz.timezone("EET")) self.write(cr, uid, ids, {'localized_date':local}, context) # save current data from the form #create serial number for the lot move = self.browse(cr, uid, ids, context=None)[0] print 'creating lot_serial: ' + str(move.lot_serial) print 'existing prodlot_id: ' + str(move.prodlot_id) if move.lot_serial: prodlot_obj = self.pool.get('stock.production.lot') prodlot_id = prodlot_obj.create(cr, uid, {'product_id': move.product_id.id, 'name': move.lot_serial }, context=context) print 'created prodlot: ' + str(prodlot_id) self.write(cr, uid, ids, {'prodlot_id': prodlot_id}, context) if context is None: print 'no context' context = {} datas = {} if not self.browse(cr, uid, ids, context=None)[0].inspected_by: raise osv.except_osv('Error', 'Aseta tarkastaja') return { 'type' : 'ir.actions.report.xml', 'report_name' : 'stock.move.extended.label', 'datas' : datas, }
def weeklyrevenue(request, template="weeklyrevenue_content"): est = pytz.timezone('US/Eastern') # <-- here now = datetime.astimezone(datetime.utcnow().replace(tzinfo=utc), tz=est) today = now.date() startofweek = today - timedelta(days=today.weekday()) user_profile = request.user.get_profile() if user_profile.isVendor(): completed_orders = Order.objects.filter( vendor=user_profile.vendor, state=COMPLETED, date_confirmed__gte=startofweek ) else: completed_orders = Order.objects.filter( buyer=request.user, state=COMPLETED, date_confirmed__gte=startofweek ) total = 0 item_count = set() order_count = set() for order in completed_orders: total += order.total entries = order.entry_set.all() for entry in entries: item_count.add(entry.listing.pk) order_count.add(order.pk) context = { "startdate": startofweek, "total": total, "item_count": len(item_count), "order_count": len(order_count), } return render_to_response(template, context, context_instance=RequestContext(request))
def sunriseset(): syd = 'Australia/Melbourne' u = datetime.utcnow() u = u.replace(tzinfo=pytz.utc) today = datetime.astimezone(u, pytz.timezone(syd)) tomorrow = today + timedelta(days=1) a = Astral() location = a['Sydney'] todaysun = location.sun(local=True, date=today) today_sunrise = todaysun['sunrise'] today_sunset = todaysun['sunset'] today_sunrise_text = "\nSunrise: " + str(today_sunrise.time()) today_sunset_text = "\nSunset: " + str(today_sunset.time()) tomorrowsun = location.sun(local=True, date=tomorrow) tomorrow_sunrise = tomorrowsun['sunrise'] tomorrow_sunset = tomorrowsun['sunset'] tomorrow_sunrise_text = "\nSunrise: " + str(tomorrow_sunrise.time()) tomorrow_sunset_text = "\nSunset: " + str(tomorrow_sunset.time()) today = (today_sunrise_text + today_sunset_text) tomorrow = (tomorrow_sunrise_text + tomorrow_sunset_text) return today, tomorrow
def long_datetime(datetime): return datetime.astimezone(g.tz).ctime() + " " + str(g.tz)
def __get_datetime(self, datetime, tz): if tz is None: return datetime return datetime.astimezone(tz)