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 get_timezone_offset_hours_from_date(self, year, month, day): """Get timezone offset in hours east of UTC (negative west of UTC) Timezone offset is dependent both on place and time - due to Daylight savings time. compute offset from UTC in hours """ import pytz # checking @ 6am local - can we do any better? local_time = pytz.timezone(self.timezone).localize(datetime(year, month, day, 6, 0, 0)) return (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0
def set_rtc_alarm(self, time: datetime.datetime, repeat: list = [0, 0, 0, 0, 0, 0, 0]) -> namedtuple: """Sets the alarm time time = datetime.datetime object repeat = list(0,0,0,0,0,0,0) with each value being 0 or 1 for Sunday-Saturday """ timestr = datetime.isoformat(time) if not datetime.utcoffset(time): timestr += "+00:00" # Build repeat string s = str() for x in repeat: # Only accept 0 or 1 if x in [0, 1]: s += str(x) else: raise ValueError repeat_dec = int(s, 2) # Convert the string to decimal from binary print(f"rtc_alarm_set {timestr} {repeat_dec}") output = self.netcat.query(f"rtc_alarm_set {timestr} {repeat_dec}") return self._nt(output)
def validate_utc(self, _key, start_date_time): """Validate that start_date_time is always UTC for consistency.""" if datetime.utcoffset(start_date_time) == timedelta(0): return start_date_time raise ValidationError( f"start_date_time {start_date_time} is not set to the UTC")
def get_timezone_offset_hours_from_date(self, year, month, day, hour=6, minute=0, seconds=0): """Get timezone offset in hours east of UTC (negative west of UTC) Timezone offset is dependent both on place and time (yes- time, not just date) - due to Daylight savings time. compute offset from UTC in hours """ import pytz local_time = pytz.timezone(self.timezone).localize( datetime(year, month, day, hour, minute, seconds)) return (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0
def test_naive_to_toronto(): dt = datetime.strptime("20201223 101010", "%Y%m%d %H%M%S") assert dt.tzinfo is None dt = utc_to_toronto(dt) assert dt.tzname() == 'EST' assert datetime.utcoffset(dt).seconds == 68400
def compute_solar_eclipses(self): jd = self.panchaanga.jd_start while 1: next_eclipse_sol = self.panchaanga.city.get_solar_eclipse_time( jd_start=jd) [y, m, dt, t] = time.jd_to_utc_gregorian( next_eclipse_sol[1][0]).to_date_fractional_hour_tuple() local_time = tz(self.panchaanga.city.timezone).localize( datetime(y, m, dt, 6, 0, 0)) # checking @ 6am local - can we do any better? tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # compute offset from UTC jd = next_eclipse_sol[1][0] + (tz_off / 24.0) jd_eclipse_solar_start = next_eclipse_sol[1][1] + (tz_off / 24.0) jd_eclipse_solar_end = next_eclipse_sol[1][4] + (tz_off / 24.0) # -1 is to not miss an eclipse that occurs after sunset on 31-Dec! if jd_eclipse_solar_start > self.panchaanga.jd_end + 1: break else: fday = int( floor(jd) - floor(self.daily_panchaangas[0].julian_day_start)) if (jd < (self.daily_panchaangas[fday].jd_sunrise + tz_off / 24.0)): fday -= 1 eclipse_solar_start = time.jd_to_utc_gregorian( jd_eclipse_solar_start).get_fractional_hour() if (jd_eclipse_solar_start - (tz_off / 24.0)) == 0.0 or \ (jd_eclipse_solar_end - (tz_off / 24.0)) == 0.0: # Move towards the next eclipse... at least the next new # moon (>=25 days away) jd += MIN_DAYS_NEXT_ECLIPSE continue solar_eclipse_str = 'sUrya-grahaNam' if self.daily_panchaangas[fday].date.get_weekday() == 0: solar_eclipse_str = '★cUDAmaNi-' + solar_eclipse_str self.daily_panchaangas[fday].festival_id_to_instance[ solar_eclipse_str] = (FestivalInstance( name=solar_eclipse_str, interval=Interval(jd_start=jd_eclipse_solar_start, jd_end=jd_eclipse_solar_end))) jd = jd + MIN_DAYS_NEXT_ECLIPSE
def test_toronto_to_toronto(): dt = pytz.timezone('America/Toronto').localize( datetime.strptime("20201223 101010", "%Y%m%d %H%M%S")) assert dt.tzinfo is not None dt = utc_to_toronto(dt) assert dt.tzname() == 'EST' assert datetime.utcoffset(dt).seconds == 68400
async def post_generate_escrow_wallet_from_request( request: web.Request) -> web.Response: """AIOHTTP Request create account xdr and presigned transaction xdr""" body = await request.json() escrow_address = request.match_info['escrow_address'] transaction_source_address = body['transaction_source_address'] provider_address = body['provider_address'] creator_address = body['creator_address'] destination_address = body['destination_address'] starting_balance = body['starting_balance'] cost_per_transaction = body['cost_per_transaction'] expiration_date = body.get('expiration_date', None) try: int_cost = Decimal(cost_per_transaction) decimal_starting_balance = Decimal(starting_balance) except InvalidOperation: raise web.HTTPBadRequest( reason= f"Can not convert to destination_address or cost_per_transaction to Decimal" ) if int_cost <= 0: raise web.HTTPBadRequest( reason=f'Parameter cost_per_transaction is not valid.') if Decimal(starting_balance) % Decimal(cost_per_transaction) != 0: raise web.HTTPBadRequest( reason= f'Parameter starting_balance is not match with cost_per_transaction.' ) if expiration_date: datetime = parser.isoparse(expiration_date) # type: ignore timezone_offset = datetime.utcoffset() if timezone_offset is None: raise web.HTTPBadRequest( reason=f'Parameter expiration date is not valid.') result = await generate_escrow_wallet( escrow_address, transaction_source_address, creator_address, destination_address, provider_address, starting_balance, cost_per_transaction, expiration_date, ) return web.json_response(result)
def get_timezone_offset_hours(self, julian_day): """Get timezone offset in hours east of UTC (negative west of UTC) Timezone offset is dependent both on place and time - due to Daylight savings time. compute offset from UTC in hours """ [y, m, dt, t] = swe.revjul(julian_day) import pytz # checking @ 6am local - can we do any better? local_time = pytz.timezone(self.timezone).localize(datetime(y, m, dt, 6, 0, 0)) return datetime.utcoffset(local_time).seconds / 3600.0
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME): """Return the timezone associated with the given `datetime` object formatted as string indicating the offset from GMT. >>> dt = datetime(2007, 4, 1, 15, 30) >>> get_timezone_gmt(dt, locale='en') u'GMT+00:00' >>> from pytz import timezone >>> tz = timezone('America/Los_Angeles') >>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz) >>> get_timezone_gmt(dt, locale='en') u'GMT-08:00' >>> get_timezone_gmt(dt, 'short', locale='en') u'-0800' The long format depends on the locale, for example in France the acronym UTC string is used instead of GMT: >>> get_timezone_gmt(dt, 'long', locale='fr_FR') u'UTC-08:00' :param datetime: the ``datetime`` object; if `None`, the current date and time in UTC is used :param width: either "long" or "short" :param locale: the `Locale` object, or a locale string :return: the GMT offset representation of the timezone :rtype: `unicode` :since: version 0.9 """ if datetime is None: datetime = datetime_.utcnow() elif isinstance(datetime, (int, long)): datetime = datetime_.utcfromtimestamp(datetime).time() if datetime.tzinfo is None: datetime = datetime.replace(tzinfo=UTC) locale = Locale.parse(locale) offset = datetime.utcoffset() seconds = offset.days * 24 * 60 * 60 + offset.seconds hours, seconds = divmod(seconds, 3600) if width == 'short': pattern = u'%+03d%02d' else: pattern = locale.zone_formats['gmt'] % '%+03d:%02d' return pattern % (hours, seconds // 60)
def set_rtc_alarm(self, time: datetime.datetime, repeat: list = [0, 0, 0, 0, 0, 0, 0]) -> bool: timestr = datetime.isoformat(time) if not datetime.utcoffset(time): timestr += "-06:00" # Build repeat string s = str() for x in repeat: # Only accept 0 or 1 if x in [0, 1]: s += str(x) else: return False repeat_dec = int(s, 2) # Convert the string to decimal from binary output = self.netcat.query(f"rtc_alarm_set {timestr} {repeat_dec}") tup = output.split(": ", 1) return tup[1] == "done"
def to_timestamp_naive(datetime_str): from dateutil.parser import parse datetime = parse(datetime_str) naive = datetime.replace(tzinfo=None) - datetime.utcoffset() return naive.isoformat(' ')
def getTodayEventsById(self, cr, uid, ids, params, timeDtFrmt, context=None): """ Plan tasks after drag&drop task on planning :param cr: database cursor :param uid: current user id :param ids: list of ids :param params: contains start_working_time : date/heure début de journée travaillée end_working_time : date/heure fin de journée start_lunch_time : date/heure début pause déjeuner end_lunch_time : date/heure fin pause déjeuner start_dt: date/heure du début de la plage souhaitée type : string key : 'officer', 'team', 'partner' calendar_id : celui de l'agent / ou celui de l'équipe, selon le type This method is used to get events on start_dt (lunch including) for officer or team (calendar_id) """ if not set(('start_working_time','end_working_time','start_lunch_time','end_lunch_time','start_dt','calendar_id')).issubset(params) : raise Exception('Erreur : il manque des paramètres pour pouvoir planifier (Heure d''embauche, heure de déjeuner...) \n Veuillez contacter votre administrateur ') #Date format passed by javascript client : date from utc. #Client swif lose the timezone because of the serialisation in JSON request (JSON.stringify) timeDtFrmtWithTmz = "%Y-%m-%dT%H:%M:%S.000Z" #Get user context context_tz = self.pool.get('res.users').read(cr,uid,[uid], ['context_tz'])[0]['context_tz'] or 'Europe/Paris' tzinfo = pytz.timezone(context_tz) events= [] todayDt = datetime.now(tzinfo) #Calculate time differencee between utc and user's timezone deltaTz = int((datetime.utcoffset(todayDt).total_seconds())/3600) #Get Start and end working time, lunch start and stop times start_dt = datetime.strptime(params['start_dt'],timeDtFrmtWithTmz) start_working_time = start_dt.replace(hour= (int(params['start_working_time'])-deltaTz),minute=0, second=0, microsecond=0) start_lunch_time = start_dt.replace( hour = (int(params['start_lunch_time'])-deltaTz),minute=0, second=0, microsecond=0 ) end_lunch_time = start_dt.replace( hour = (int(params['end_lunch_time'])-deltaTz),minute=0, second=0, microsecond=0 ) #Add in list events.append({'title': "lunchTime", 'date_start': start_lunch_time, 'date_end': end_lunch_time}) end_working_time = start_dt.replace( hour = (int(params['end_working_time'])-deltaTz),minute=0, second=0, microsecond=0 ) events.append({'title': "end_working_time", 'date_start': end_working_time, 'date_end': end_working_time}) task_ids = [] if params['type'] == 'team': #Get all tasks on 'start_dt' for team task_ids = self.search(cr,uid, ['&',('date_start','>=', datetime.strftime(start_working_time,timeDtFrmt)), ('date_start','<=', datetime.strftime(end_working_time,timeDtFrmt)), '|',('team_id','=',params['calendar_id']), ('user_id','in', self.pool.get('openstc.team').read(cr, uid, params['calendar_id'], ['user_ids'])['user_ids'] ) ]) elif params['type'] == 'officer': #Get all tasks on 'start_dt' for officer task_ids = self.search(cr,uid, ['&',('date_start','>=', datetime.strftime(start_working_time,timeDtFrmt)), ('date_start','<=', datetime.strftime(end_working_time,timeDtFrmt)), '|',('user_id','=', params['calendar_id']), ('team_id','in', self.pool.get('res.users').read(cr, uid, params['calendar_id'], ['team_ids'])['team_ids'] ) ]) else: #Get all tasks on 'start_dt' for officer task_ids = self.search(cr,uid, ['&',('date_start','>=', datetime.strftime(start_working_time,timeDtFrmt)), ('date_start','<=', datetime.strftime(end_working_time,timeDtFrmt)), ('partner_id','=', params['calendar_id']) ]) tasks = self.read(cr,uid,task_ids, ['name','date_start','date_end']) #Add tasks in list for task in tasks : events.append({'title': task['name'], 'date_start': datetime.strptime(task['date_start'],timeDtFrmt), 'date_end': datetime.strptime(task['date_end'],timeDtFrmt) }) #Sort task events.sort(key=operator.itemgetter('date_start')) params['events'] = events params['start_dt'] = start_dt #Return tasks return events
def compute_lunar_eclipses(self): # Set location jd = self.panchaanga.jd_start while 1: next_eclipse_lun = self.panchaanga.city.get_lunar_eclipse_time(jd) [y, m, dt, t] = time.jd_to_utc_gregorian( next_eclipse_lun[1][0]).to_date_fractional_hour_tuple() local_time = tz(self.panchaanga.city.timezone).localize( datetime(y, m, dt, 6, 0, 0)) # checking @ 6am local - can we do any better? This is crucial, # since DST changes before 6 am tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # compute offset from UTC jd = next_eclipse_lun[1][0] + (tz_off / 24.0) jd_eclipse_lunar_start = next_eclipse_lun[1][2] + (tz_off / 24.0) jd_eclipse_lunar_end = next_eclipse_lun[1][3] + (tz_off / 24.0) # -1 is to not miss an eclipse that occurs after sunset on 31-Dec! if jd_eclipse_lunar_start > self.panchaanga.jd_end: break else: if (jd_eclipse_lunar_start - (tz_off / 24.0)) == 0.0 or \ (jd_eclipse_lunar_end - (tz_off / 24.0)) == 0.0: # Move towards the next eclipse... at least the next full # moon (>=25 days away) jd += MIN_DAYS_NEXT_ECLIPSE continue fday = int( floor(jd_eclipse_lunar_start) - floor(self.panchaanga.jd_start) + 1) # print '%%', jd, fday, self.date_str_to_panchaanga[fday].jd_sunrise, # self.date_str_to_panchaanga[fday-1].jd_sunrise if (jd < (self.daily_panchaangas[fday].jd_sunrise + tz_off / 24.0)): fday -= 1 # print '%%', jd, fday, self.date_str_to_panchaanga[fday].jd_sunrise, # self.date_str_to_panchaanga[fday-1].jd_sunrise, eclipse_lunar_start, # eclipse_lunar_end jd_moonrise_eclipse_day = self.panchaanga.city.get_rising_time( julian_day_start=self.daily_panchaangas[fday].jd_sunrise, body=Graha.MOON) + (tz_off / 24.0) jd_moonset_eclipse_day = self.panchaanga.city.get_rising_time( julian_day_start=jd_moonrise_eclipse_day, body=Graha.MOON) + (tz_off / 24.0) if jd_eclipse_lunar_end < jd_moonrise_eclipse_day or \ jd_eclipse_lunar_start > jd_moonset_eclipse_day: # Move towards the next eclipse... at least the next full # moon (>=25 days away) jd += MIN_DAYS_NEXT_ECLIPSE continue if Graha.singleton(Graha.MOON).get_longitude( jd_eclipse_lunar_end) < Graha.singleton( Graha.SUN).get_longitude(jd_eclipse_lunar_end): grasta = 'rAhugrasta' else: grasta = 'kEtugrasta' lunar_eclipse_str = 'candra-grahaNam~(' + grasta + ')' if self.daily_panchaangas[fday].date.get_weekday() == 1: lunar_eclipse_str = '★cUDAmaNi-' + lunar_eclipse_str self.daily_panchaangas[fday].festival_id_to_instance[ lunar_eclipse_str] = (FestivalInstance( name=lunar_eclipse_str, interval=Interval(jd_start=jd_eclipse_lunar_start, jd_end=jd_eclipse_lunar_end))) jd += MIN_DAYS_NEXT_ECLIPSE
def writeMonthlyTeX(panchangam, template_file): """Write out the panchangam TeX using a specified template """ day_colours = {0: 'blue', 1: 'blue', 2: 'blue', 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue'} month = {1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER', 10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER'} MON = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} WDAY = {0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat'} template_lines = template_file.readlines() for i in range(0, len(template_lines) - 3): print(template_lines[i][:-1]) samvatsara_id = (panchangam.year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = '%s–%s' % (jyotisha.panchangam.temporal.NAMES['SAMVATSARA_NAMES'][panchangam.script][samvatsara_id], jyotisha.panchangam.temporal.NAMES['SAMVATSARA_NAMES'][panchangam.script][(samvatsara_id % 60) + 1]) print('\\mbox{}') print('{\\font\\x="Noto Sans UI" at 60 pt\\x %d\\\\[0.5cm]}' % panchangam.year) print('\\mbox{\\font\\x="Siddhanta:script=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names) print('\\mbox{\\font\\x="Siddhanta:script=deva" at 32 pt\\x %s } %%' % jyotisha.custom_transliteration.tr('kali', panchangam.script)) print('{\\font\\x="Noto Sans UI" at 32 pt\\x %d–%d\\\\[0.5cm]}' % (panchangam.year + 3100, panchangam.year + 3101)) print('{\\font\\x="Noto Sans UI" at 48 pt\\x \\uppercase{%s}\\\\[0.2cm]}' % panchangam.city.name) print('{\\font\\x="Noto Sans UI" at 16 pt\\x {%s}\\\\[0.5cm]}' % jyotisha.custom_transliteration.print_lat_lon(panchangam.city.latstr, panchangam.city.lonstr)) print('\hrule') print('\\newpage') print('\\centering') print('\\centerline{\\LARGE {{%s}}}' % jyotisha.custom_transliteration.tr('mAsAntara-vizESAH', panchangam.script)) print('\\begin{multicols*}{3}') print('\\TrickSupertabularIntoMulticols') print('\\begin{supertabular}' + '{>{\\sffamily}r>{\\sffamily}r>{\\sffamily}c>{\\hangindent=2ex}p{8cm}}') mlast = 1 for d in range(1, jyotisha.panchangam.temporal.MAX_SZ - 1): [y, m, dt, t] = swe.revjul(panchangam.jd_start + d - 1) # checking @ 6am local - can we do any better? local_time = tz(panchangam.city.timezone).localize(datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = panchangam.jd_start - tz_off / 24.0 + d - 1 if len(panchangam.festivals[d]) != 0: if m != mlast: mlast = m print('\\\\') print('%s & %s & %s & {\\raggedright %s} \\\\' % (MON[m], dt, WDAY[panchangam.weekday[d]], '\\\\'.join([jyotisha.custom_transliteration.tr(f, panchangam.script) for f in sorted(set(panchangam.festivals[d]))]))) if m == 12 and dt == 31: break print('\\end{supertabular}') print('\\end{multicols*}') print('\\renewcommand{\\tamil}[1]{%') print('{\\fontspec[Scale=0.9,FakeStretch=0.9]{Noto Sans Tamil}\\fontsize{7}{12}\\selectfont #1}}') # print('\\clearpage') for d in range(1, jyotisha.panchangam.temporal.MAX_SZ - 1): [y, m, dt, t] = swe.revjul(panchangam.jd_start + d - 1) # checking @ 6am local - can we do any better? local_time = tz(panchangam.city.timezone).localize(datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = panchangam.jd_start - (tz_off / 24.0) + d - 1 if dt == 1: if m > 1: if panchangam.weekday[d] != 0: # Space till Sunday for i in range(panchangam.weekday[d], 6): print("{} &") print("\\\\ \hline") print('\end{tabular}') print('\n\n') # Begin tabular print('\\begin{tabular}{|c|c|c|c|c|c|c|}') print('\multicolumn{7}{c}{\Large \\bfseries \sffamily %s %s}\\\\[3mm]' % ( month[m], y)) print('\hline') WDAY_NAMES = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] print(' & '.join(['\\textbf{\\textsf{%s}}' % _day for _day in WDAY_NAMES]) + ' \\\\ \hline') # Blanks for previous weekdays for i in range(0, panchangam.weekday[d]): print("{} &") tithi_data_str = '' for tithi_ID, tithi_end_jd in panchangam.tithi_data[d]: # if tithi_data_str != '': # tithi_data_str += '\\hspace{2ex}' tithi = '\moon[scale=0.6]{%d}\\hspace{2pt}' % (tithi_ID) + \ jyotisha.panchangam.temporal.NAMES['TITHI_NAMES'][panchangam.script][tithi_ID] if tithi_end_jd is None: tithi_data_str = '%s\\mbox{%s\\To{}%s}' % \ (tithi_data_str, tithi, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: tithi_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (tithi_data_str, tithi, jyotisha.panchangam.temporal.Time(24 * (tithi_end_jd - jd)).toString(format=panchangam.fmt), '\\hspace{2ex}') nakshatram_data_str = '' for nakshatram_ID, nakshatram_end_jd in panchangam.nakshatram_data[d]: # if nakshatram_data_str != '': # nakshatram_data_str += '\\hspace{2ex}' nakshatram = jyotisha.panchangam.temporal.NAMES['NAKSHATRAM_NAMES'][panchangam.script][nakshatram_ID] if nakshatram_end_jd is None: nakshatram_data_str = '%s\\mbox{%s\\To{}%s}' % \ (nakshatram_data_str, nakshatram, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: nakshatram_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (nakshatram_data_str, nakshatram, jyotisha.panchangam.temporal.Time(24 * (nakshatram_end_jd - jd)).toString(format=panchangam.fmt), '\\hspace{2ex}') yogam_data_str = '' for yogam_ID, yogam_end_jd in panchangam.yogam_data[d]: # if yogam_data_str != '': # yogam_data_str += '\\hspace{2ex}' yogam = jyotisha.panchangam.temporal.NAMES['YOGAM_NAMES'][panchangam.script][yogam_ID] if yogam_end_jd is None: yogam_data_str = '%s\\mbox{%s\\To{}%s}' % \ (yogam_data_str, yogam, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: yogam_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (yogam_data_str, yogam, jyotisha.panchangam.temporal.Time(24 * (yogam_end_jd - jd)).toString(format=panchangam.fmt), '\\hspace{2ex}') karanam_data_str = '' for numKaranam, (karanam_ID, karanam_end_jd) in enumerate(panchangam.karanam_data[d]): # if numKaranam == 1: # karanam_data_str += '\\hspace{2ex}' if numKaranam == 2: karanam_data_str = karanam_data_str + '\\\\' karanam = jyotisha.panchangam.temporal.NAMES['KARANAM_NAMES'][panchangam.script][karanam_ID] if karanam_end_jd is None: karanam_data_str = '%s\\mbox{%s\\To{}%s}' % \ (karanam_data_str, karanam, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: karanam_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (karanam_data_str, karanam, jyotisha.panchangam.temporal.Time(24 * (karanam_end_jd - jd)).toString(format=panchangam.fmt), '\\hspace{2ex}') sunrise = jyotisha.panchangam.temporal.Time(24 * (panchangam.jd_sunrise[d] - jd)).toString(format=panchangam.fmt) sunset = jyotisha.panchangam.temporal.Time(24 * (panchangam.jd_sunset[d] - jd)).toString(format=panchangam.fmt) sangava = jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['saGgava'][0] - jd)).toString(format=panchangam.fmt) rahu = '%s--%s' % ( jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['rahu'][0] - jd)).toString(format=panchangam.fmt), jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['rahu'][1] - jd)).toString(format=panchangam.fmt)) yama = '%s--%s' % ( jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['yama'][0] - jd)).toString(format=panchangam.fmt), jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['yama'][1] - jd)).toString(format=panchangam.fmt)) print('\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[panchangam.weekday[d]], dt, panchangam.month_data[d], jyotisha.panchangam.temporal.get_chandra_masa(panchangam.lunar_month[d], jyotisha.panchangam.temporal.NAMES, panchangam.script))) print('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, sangava)) print('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatram_data_str, yogam_data_str, karanam_data_str)) print('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! print('{%s}' % '\\eventsep '.join( [jyotisha.custom_transliteration.tr(f, panchangam.script) for f in sorted(set(panchangam.festivals[d]))])) if panchangam.weekday[d] == 6: print("\\\\ \hline") else: print("&") if m == 12 and dt == 31: break # For debugging specific dates # if m==4 and dt==10: # break for i in range(panchangam.weekday[d] + 1, 6): print("{} &") if panchangam.weekday[d] != 6: print("\\\\ \hline") print('\end{tabular}') print('\n\n') print(template_lines[-2][:-1]) print(template_lines[-1][:-1])
def emit(panchaanga, time_format="hh:mm", languages=None, scripts=None, output_stream=None): """Write out the panchaanga TeX using a specified template """ # day_colours = {0: 'blue', 1: 'blue', 2: 'blue', # 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue'} compute_lagnams = panchaanga.computation_system.festival_options.set_lagnas if scripts is None: scripts = [sanscript.DEVANAGARI] if languages is None: languages = ["sa"] template_file = open( os.path.join(os.path.dirname(__file__), 'templates/daily_cal_template.tex')) template_lines = template_file.readlines() for i in range(len(template_lines)): print(template_lines[i][:-1], file=output_stream) year = panchaanga.start_date.year logging.debug(year) samvatsara_id = (year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = ( names.NAMES['SAMVATSARA_NAMES']['sa'][scripts[0]][samvatsara_id], names.NAMES['SAMVATSARA_NAMES']['sa'][scripts[0]][(samvatsara_id % 60) + 1]) yname = samvatsara_names[0] # Assign year name until Mesha Sankranti set_top_content(output_stream, panchaanga, samvatsara_names, scripts, year) daily_panchaangas = panchaanga.daily_panchaangas_sorted() for d, daily_panchaanga in enumerate(daily_panchaangas): if daily_panchaanga.date < panchaanga.start_date or daily_panchaanga.date > panchaanga.end_date: continue [y, m, dt] = [ daily_panchaanga.date.year, daily_panchaanga.date.month, daily_panchaanga.date.day ] # checking @ 6am local - can we do any better? local_time = tz(panchaanga.city.timezone).localize( datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 tithi_data_str = get_tithi_data_str(daily_panchaanga, scripts, time_format) nakshatra_data_str = get_nakshatra_data_str(daily_panchaanga, scripts, time_format) rashi_data_str = get_raashi_data_str(daily_panchaanga, scripts, time_format) lagna_data_str = get_lagna_data_str( daily_panchaanga, scripts, time_format) if compute_lagnams else '' yoga_data_str = get_yoga_data_str(daily_panchaanga, scripts, time_format) karana_data_str = get_karaNa_data_str(daily_panchaanga, scripts, time_format) gulika, rahu, yama, raatri_gulika, raatri_yama = get_raahu_yama_gulika_strings( daily_panchaanga, time_format) if daily_panchaanga.solar_sidereal_date_sunset.month == 1: # Flip the year name for the remaining days yname = samvatsara_names[1] # Assign samvatsara, ayana, rtu # sar_data = '{%s}{%s}{%s}' % (yname, names.NAMES['AYANA_NAMES']['sa'][ scripts[0]][daily_panchaanga.solar_sidereal_date_sunset. month], names.NAMES['RTU_NAMES']['sa'][scripts[0]][ daily_panchaanga.solar_sidereal_date_sunset.month]) if daily_panchaanga.solar_sidereal_date_sunset.month_transition is None: month_end_str = '' else: _m = daily_panchaangas[d - 1].solar_sidereal_date_sunset.month if daily_panchaanga.solar_sidereal_date_sunset.month_transition >= daily_panchaangas[ d + 1].jd_sunrise: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}{%s}}' % ( names.NAMES['RASHI_NAMES']['sa'][scripts[0]][_m], time.Hour( 24 * (daily_panchaanga.solar_sidereal_date_sunset. month_transition - daily_panchaangas[d + 1].julian_day_start)).to_string( format=time_format)) else: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}{%s}}' % ( names.NAMES['RASHI_NAMES']['sa'][scripts[0]][_m], time.Hour(24 * (daily_panchaanga.solar_sidereal_date_sunset. month_transition - daily_panchaanga.julian_day_start)).to_string( format=time_format)) month_data = '\\sunmonth{%s}{%d}{%s}' % ( names.NAMES['RASHI_NAMES']['sa'][scripts[0]][ daily_panchaanga.solar_sidereal_date_sunset.month], daily_panchaanga.solar_sidereal_date_sunset.day, month_end_str) print('\\caldata{%s}{%s}{%s{%s}{%s}{%s}%s}' % (names.month_map[m].upper(), dt, month_data, names.get_chandra_masa( daily_panchaanga.lunar_month_sunrise.index, scripts[0]), names.NAMES['RTU_NAMES']['sa'][scripts[0]][int( ceil(daily_panchaanga.lunar_month_sunrise.index))], names.NAMES['VARA_NAMES']['sa'][scripts[0]][ daily_panchaanga.date.get_weekday()], sar_data), file=output_stream) stream_sun_moon_rise_data(daily_panchaanga, output_stream, time_format) stream_daylength_based_periods(daily_panchaanga, output_stream, time_format) print('{\\tnykdata{%s}%%\n{%s}{%s}%%\n{%s}%%\n{%s}{%s}\n}' % (tithi_data_str, nakshatra_data_str, rashi_data_str, yoga_data_str, karana_data_str, lagna_data_str), file=output_stream) print_festivals_to_stream(daily_panchaanga, output_stream, panchaanga, languages, scripts) print('{%s} ' % names.weekday_short_map[daily_panchaanga.date.get_weekday()], file=output_stream) print('\\cfoot{\\rygdata{%s}{%s}{%s}}' % (rahu, yama, gulika), file=output_stream) if m == 12 and dt == 31: break print('\\end{document}', file=output_stream)
def utcoffset(self): """Returns our offset from UTC, including any leap-second adjustments.""" return datetime.utcoffset(self) + timedelta( seconds=self.__leapseconds(self.tzinfo))
def writeDailyTeX(panchangam, template_file, compute_lagnams=True, output_stream=None): """Write out the panchangam TeX using a specified template """ # day_colours = {0: 'blue', 1: 'blue', 2: 'blue', # 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue'} month = { 1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER', 10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER' } WDAY = { 0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat' } template_lines = template_file.readlines() for i in range(len(template_lines)): print(template_lines[i][:-1], file=output_stream) samvatsara_id = (panchangam.year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = (jyotisha.panchangam.temporal.NAMES['SAMVATSARA_NAMES'][ panchangam.script][samvatsara_id], jyotisha.panchangam.temporal.NAMES['SAMVATSARA_NAMES'][ panchangam.script][(samvatsara_id % 60) + 1]) yname = samvatsara_names[0] # Assign year name until Mesha Sankranti print('\\mbox{}', file=output_stream) print('\\renewcommand{\\yearname}{%d}' % panchangam.year, file=output_stream) print('\\begin{center}', file=output_stream) print('{\\sffamily \\fontsize{80}{80}\\selectfont %d\\\\[0.5cm]}' % panchangam.year, file=output_stream) print('\\mbox{\\fontsize{48}{48}\\selectfont %s–%s}\\\\' % samvatsara_names, file=output_stream) print('\\mbox{\\fontsize{32}{32}\\selectfont %s } %%' % jyotisha.custom_transliteration.tr('kali', panchangam.script), file=output_stream) print( '{\\sffamily \\fontsize{43}{43}\\selectfont %d–%d\\\\[0.5cm]}\n\\hrule\n\\vspace{0.2cm}' % (panchangam.year + 3100, panchangam.year + 3101), file=output_stream) print( '{\\sffamily \\fontsize{50}{50}\\selectfont \\uppercase{%s}\\\\[0.2cm]}' % panchangam.city.name, file=output_stream) print('{\\sffamily \\fontsize{23}{23}\\selectfont {%s}\\\\[0.2cm]}' % jyotisha.custom_transliteration.print_lat_lon( panchangam.city.latitude, panchangam.city.longitude), file=output_stream) print('\\hrule', file=output_stream) print('\\end{center}', file=output_stream) print('\\clearpage\\pagestyle{fancy}', file=output_stream) panchangam.get_kaalas() for d in range(1, jyotisha.panchangam.temporal.MAX_SZ - 1): [y, m, dt, t] = swe.revjul(panchangam.jd_start_utc + d - 1) # checking @ 6am local - can we do any better? local_time = tz(panchangam.city.timezone).localize( datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = panchangam.jd_midnight[d] tithi_data_str = '' for tithi_ID, tithi_end_jd in panchangam.tithi_data[d]: # if tithi_data_str != '': # tithi_data_str += '\\hspace{1ex}' tithi = '\\raisebox{-1pt}{\moon[scale=0.8]{%d}}\\hspace{2pt}' % (tithi_ID) + \ jyotisha.panchangam.temporal.NAMES['TITHI_NAMES'][panchangam.script][tithi_ID] if tithi_end_jd is None: tithi_data_str = '%s\\mbox{%s\\To{}%s}' % \ (tithi_data_str, tithi, jyotisha.custom_transliteration.tr('ahOrAtram (tridinaspRk)', panchangam.script)) else: tithi_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}\\hspace{1ex}' % \ (tithi_data_str, tithi, jyotisha.panchangam.temporal.Time(24 * (tithi_end_jd - panchangam.jd_sunrise[d])).toString(format='gg-pp'), jyotisha.panchangam.temporal.Time(24 * (tithi_end_jd - jd)).toString(format=panchangam.fmt)) nakshatram_data_str = '' for nakshatram_ID, nakshatram_end_jd in panchangam.nakshatram_data[d]: if nakshatram_data_str != '': nakshatram_data_str += '\\hspace{1ex}' nakshatram = jyotisha.panchangam.temporal.NAMES[ 'NAKSHATRAM_NAMES'][panchangam.script][nakshatram_ID] if nakshatram_end_jd is None: nakshatram_data_str = '%s\\mbox{%s\\To{}%s}' % \ (nakshatram_data_str, nakshatram, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: nakshatram_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}' % \ (nakshatram_data_str, nakshatram, jyotisha.panchangam.temporal.Time(24 * (nakshatram_end_jd - panchangam.jd_sunrise[d])).toString(format='gg-pp'), jyotisha.panchangam.temporal.Time(24 * (nakshatram_end_jd - jd)).toString(format=panchangam.fmt)) rashi_data_str = '' for rashi_ID, rashi_end_jd in panchangam.rashi_data[d]: # if rashi_data_str != '': # rashi_data_str += '\\hspace{1ex}' rashi = jyotisha.panchangam.temporal.NAMES['RASHI_SUFFIXED_NAMES'][ panchangam.script][rashi_ID] if rashi_end_jd is None: rashi_data_str = '%s\\mbox{%s}' % (rashi_data_str, rashi) else: rashi_data_str = '%s\\mbox{%s \\RIGHTarrow \\textsf{%s}}' % \ (rashi_data_str, rashi, jyotisha.panchangam.temporal.Time(24 * (rashi_end_jd - jd)).toString(format=panchangam.fmt)) if compute_lagnams: lagna_data_str = 'लग्नम्–' for lagna_ID, lagna_end_jd in panchangam.lagna_data[d]: lagna = jyotisha.panchangam.temporal.NAMES['RASHI_NAMES'][ panchangam.script][lagna_ID] lagna_data_str = '%s\\mbox{%s\\RIGHTarrow\\textsf{%s}} ' % \ (lagna_data_str, lagna, jyotisha.panchangam.temporal.Time(24 * (lagna_end_jd - jd)).toString(format=panchangam.fmt)) yoga_data_str = '' for yoga_ID, yoga_end_jd in panchangam.yoga_data[d]: # if yoga_data_str != '': # yoga_data_str += '\\hspace{1ex}' yoga = jyotisha.panchangam.temporal.NAMES['YOGA_NAMES'][ panchangam.script][yoga_ID] if yoga_end_jd is None: yoga_data_str = '%s\\mbox{%s\\To{}%s}' % \ (yoga_data_str, yoga, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: yoga_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}\\hspace{1ex}' % \ (yoga_data_str, yoga, jyotisha.panchangam.temporal.Time(24 * (yoga_end_jd - panchangam.jd_sunrise[d])).toString(format='gg-pp'), jyotisha.panchangam.temporal.Time(24 * (yoga_end_jd - jd)).toString(format=panchangam.fmt)) if yoga_end_jd is not None: yoga_data_str += '\\mbox{%s\\Too{}}' % ( jyotisha.panchangam.temporal.NAMES['YOGA_NAMES'][ panchangam.script][(yoga_ID % 27) + 1]) karanam_data_str = '' for numKaranam, (karanam_ID, karanam_end_jd) in enumerate( panchangam.karanam_data[d]): # if numKaranam == 1: # karanam_data_str += '\\hspace{1ex}' karanam = jyotisha.panchangam.temporal.NAMES['KARANAM_NAMES'][ panchangam.script][karanam_ID] if karanam_end_jd is None: karanam_data_str = '%s\\mbox{%s\\To{}%s}' % \ (karanam_data_str, karanam, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: karanam_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}\\hspace{1ex}' % \ (karanam_data_str, karanam, jyotisha.panchangam.temporal.Time(24 * (karanam_end_jd - panchangam.jd_sunrise[d])).toString(format='gg-pp'), jyotisha.panchangam.temporal.Time(24 * (karanam_end_jd - jd)).toString(format=panchangam.fmt)) if karanam_end_jd is not None: karanam_data_str += '\\mbox{%s\\Too{}}' % ( jyotisha.panchangam.temporal.NAMES['KARANAM_NAMES'][ panchangam.script][(karanam_ID % 60) + 1]) sunrise = jyotisha.panchangam.temporal.Time( 24 * (panchangam.jd_sunrise[d] - jd)).toString(format=panchangam.fmt) sunset = jyotisha.panchangam.temporal.Time( 24 * (panchangam.jd_sunset[d] - jd)).toString(format=panchangam.fmt) moonrise = jyotisha.panchangam.temporal.Time( 24 * (panchangam.jd_moonrise[d] - jd)).toString(format=panchangam.fmt) moonset = jyotisha.panchangam.temporal.Time( 24 * (panchangam.jd_moonset[d] - jd)).toString(format=panchangam.fmt) braahma = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['braahma'][0] - jd)).toString( format=panchangam.fmt) pratahsandhya = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['prAtaH sandhyA'][0] - jd)).toString( format=panchangam.fmt) pratahsandhya_end = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['prAtaH sandhyA end'][0] - jd)).toString( format=panchangam.fmt) sangava = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['saGgava'][0] - jd)).toString( format=panchangam.fmt) madhyaahna = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['madhyAhna'][0] - jd)).toString( format=panchangam.fmt) madhyahnika_sandhya = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['mAdhyAhnika sandhyA'][0] - jd)).toString( format=panchangam.fmt) madhyahnika_sandhya_end = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['mAdhyAhnika sandhyA end'][0] - jd)).toString(format=panchangam.fmt) aparahna = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['aparAhna'][0] - jd)).toString( format=panchangam.fmt) sayahna = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['sAyAhna'][0] - jd)).toString( format=panchangam.fmt) sayamsandhya = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['sAyaM sandhyA'][0] - jd)).toString( format=panchangam.fmt) sayamsandhya_end = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['sAyaM sandhyA end'][0] - jd)).toString( format=panchangam.fmt) ratriyama1 = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['rAtri yAma 1'][0] - jd)).toString( format=panchangam.fmt) sayana_time = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['zayana'][0] - jd)).toString( format=panchangam.fmt) dinanta = jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['dinAnta'][0] - jd)).toString( format=panchangam.fmt) rahu = '%s--%s' % (jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['rahu'][0] - jd)).toString( format=panchangam.fmt), jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['rahu'][1] - jd)).toString(format=panchangam.fmt)) yama = '%s--%s' % (jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['yama'][0] - jd)).toString( format=panchangam.fmt), jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['yama'][1] - jd)).toString(format=panchangam.fmt)) gulika = '%s--%s' % (jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['gulika'][0] - jd)).toString( format=panchangam.fmt), jyotisha.panchangam.temporal.Time( 24 * (panchangam.kaalas[d]['gulika'][1] - jd)).toString(format=panchangam.fmt)) if panchangam.solar_month[d] == 1: # Flip the year name for the remaining days yname = samvatsara_names[1] # Assign samvatsara, ayana, rtu # sar_data = '{%s}{%s}{%s}' % ( yname, jyotisha.panchangam.temporal.NAMES['AYANA_NAMES'][ panchangam.script][panchangam.solar_month[d]], jyotisha.panchangam.temporal.NAMES['RTU_NAMES'][panchangam.script][ panchangam.solar_month[d]]) if panchangam.solar_month_end_time[d] is None: month_end_str = '' else: _m = panchangam.solar_month[d - 1] if panchangam.solar_month_end_time[d] >= panchangam.jd_sunrise[d + 1]: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.panchangam.temporal.NAMES['RASHI_NAMES'][ panchangam.script][_m], jyotisha.panchangam.temporal.Time( 24 * (panchangam.solar_month_end_time[d] - panchangam.jd_midnight[d + 1])).toString( format=panchangam.fmt)) else: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.panchangam.temporal.NAMES['RASHI_NAMES'][ panchangam.script][_m], jyotisha.panchangam.temporal.Time( 24 * (panchangam.solar_month_end_time[d] - panchangam.jd_midnight[d])).toString( format=panchangam.fmt)) month_data = '\\sunmonth{%s}{%d}{%s}' % ( jyotisha.panchangam.temporal.NAMES['RASHI_NAMES'][ panchangam.script][panchangam.solar_month[d]], panchangam.solar_month_day[d], month_end_str) print('\\caldata{%s}{%s}{%s{%s}{%s}{%s}%s}' % (month[m], dt, month_data, jyotisha.panchangam.temporal.get_chandra_masa( panchangam.lunar_month[d], jyotisha.panchangam.temporal.NAMES, panchangam.script), jyotisha.panchangam.temporal.NAMES['RTU_NAMES'][ panchangam.script][int(ceil(panchangam.lunar_month[d]))], jyotisha.panchangam.temporal.NAMES['VARA_NAMES'][ panchangam.script][panchangam.weekday[d]], sar_data), file=output_stream) if panchangam.jd_moonrise[d] > panchangam.jd_sunrise[d + 1]: moonrise = '---' if panchangam.jd_moonset[d] > panchangam.jd_sunrise[d + 1]: moonset = '---' if panchangam.jd_moonrise[d] < panchangam.jd_moonset[d]: print('{\\sunmoonrsdata{%s}{%s}{%s}{%s}' % (sunrise, sunset, moonrise, moonset), file=output_stream) else: print('{\\sunmoonsrdata{%s}{%s}{%s}{%s}' % (sunrise, sunset, moonrise, moonset), file=output_stream) print('{\kalas{%s %s %s %s %s %s %s %s %s %s %s %s %s %s}}}' % (braahma, pratahsandhya, pratahsandhya_end, sangava, madhyahnika_sandhya, madhyahnika_sandhya_end, madhyaahna, aparahna, sayahna, sayamsandhya, sayamsandhya_end, ratriyama1, sayana_time, dinanta), file=output_stream) if compute_lagnams: print('{\\tnykdata{%s}%%\n{%s}{%s}%%\n{%s}%%\n{%s}{%s}\n}' % (tithi_data_str, nakshatram_data_str, rashi_data_str, yoga_data_str, karanam_data_str, lagna_data_str), file=output_stream) else: print( '{\\tnykdata{%s}%%\n{%s}{%s}%%\n{%s}%%\n{%s}{\\scriptsize %s}\n}' % (tithi_data_str, nakshatram_data_str, rashi_data_str, yoga_data_str, karanam_data_str, ''), file=output_stream) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! print('{%s}' % '\\eventsep '.join([ jyotisha.custom_transliteration.tr(f, panchangam.script).replace( '★', '$^\\star$') for f in sorted(set(panchangam.festivals[d])) ]), file=output_stream) print('{%s} ' % WDAY[panchangam.weekday[d]], file=output_stream) print('\\cfoot{\\rygdata{%s}{%s}{%s}}' % (rahu, yama, gulika), file=output_stream) if m == 12 and dt == 31: break print('\\end{document}', file=output_stream)
def assign_ekaadashii_vratam(self): for d in range(self.panchaanga.duration_prior_padding, self.panchaanga.duration + 1): [y, m, dt, t] = time.jd_to_utc_gregorian(self.panchaanga.jd_start + d - 1).to_date_fractional_hour_tuple() # checking @ 6am local - can we do any better? local_time = tz(self.panchaanga.city.timezone).localize( datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # EKADASHI Vratam # One of two consecutive tithis must appear @ sunrise! if (self.daily_panchaangas[d].sunrise_day_angas.tithi_at_sunrise. index % 15) == 10 or (self.daily_panchaangas[d].sunrise_day_angas. tithi_at_sunrise.index % 15) == 11: yati_ekaadashii_fday = smaarta_ekaadashii_fday = vaishnava_ekaadashii_fday = None ekaadashii_tithi_days = [ x.sunrise_day_angas.tithi_at_sunrise.index % 15 for x in self.daily_panchaangas[d:d + 3] ] if self.daily_panchaangas[ d].sunrise_day_angas.tithi_at_sunrise.index > 15: ekaadashii_paksha = 'krishna' else: ekaadashii_paksha = 'shukla' if ekaadashii_tithi_days in [[11, 11, 12], [10, 12, 12]]: smaarta_ekaadashii_fday = d + 1 tithi_arunodayam = tithi.get_tithi( self.daily_panchaangas[d + 1].jd_sunrise - (1 / 15.0) * (self.daily_panchaangas[d + 1].jd_sunrise - self.daily_panchaangas[d].jd_sunrise)).index if tithi_arunodayam % 15 == 10: vaishnava_ekaadashii_fday = d + 2 else: vaishnava_ekaadashii_fday = d + 1 elif ekaadashii_tithi_days in [[10, 12, 13], [11, 12, 13], [11, 12, 12], [11, 12, 14]]: smaarta_ekaadashii_fday = d tithi_arunodayam = temporal.tithi.get_tithi( self.daily_panchaangas[d].jd_sunrise - (1 / 15.0) * (self.daily_panchaangas[d].jd_sunrise - self.daily_panchaangas[d - 1].jd_sunrise)).index if tithi_arunodayam % 15 == 11 and ekaadashii_tithi_days in [ [11, 12, 13], [11, 12, 14] ]: vaishnava_ekaadashii_fday = d else: vaishnava_ekaadashii_fday = d + 1 elif ekaadashii_tithi_days in [[10, 11, 13], [11, 11, 13]]: smaarta_ekaadashii_fday = d vaishnava_ekaadashii_fday = d + 1 yati_ekaadashii_fday = d + 1 else: pass # These combinations are taken care of, either in the past or future. # if ekaadashii_tithi_days == [10, 11, 12]: # logging.debug('Not assigning. Maybe tomorrow?') # else: # logging.debug(('!!', d, ekaadashii_tithi_days)) if yati_ekaadashii_fday == smaarta_ekaadashii_fday == vaishnava_ekaadashii_fday is None: # Must have already assigned pass elif yati_ekaadashii_fday is None: if smaarta_ekaadashii_fday == vaishnava_ekaadashii_fday: # It's sarva ekaadashii self.festival_id_to_days[ 'sarva-' + names.get_ekaadashii_name( ekaadashii_paksha, self.daily_panchaangas[d]. lunar_month_sunrise.index)].add( self.daily_panchaangas[ smaarta_ekaadashii_fday].date) if ekaadashii_paksha == 'shukla': if self.daily_panchaangas[ d].solar_sidereal_date_sunset.month == 9: self.festival_id_to_days[ 'sarva-vaikuNTha-EkAdazI'].add( self.daily_panchaangas[ smaarta_ekaadashii_fday].date) else: self.festival_id_to_days[ 'smArta-' + names.get_ekaadashii_name( ekaadashii_paksha, self.daily_panchaangas[d]. lunar_month_sunrise.index)].add( self.daily_panchaangas[ smaarta_ekaadashii_fday].date) self.festival_id_to_days[ 'vaiSNava-' + names.get_ekaadashii_name( ekaadashii_paksha, self.daily_panchaangas[d]. lunar_month_sunrise.index)].add( self.daily_panchaangas[ vaishnava_ekaadashii_fday].date) if ekaadashii_paksha == 'shukla': if self.daily_panchaangas[ d].solar_sidereal_date_sunset.month == 9: self.festival_id_to_days[ 'smArta-vaikuNTha-EkAdazI'].add( self.daily_panchaangas[ smaarta_ekaadashii_fday].date) self.festival_id_to_days[ 'vaiSNava-vaikuNTha-EkAdazI'].add( self.daily_panchaangas[ vaishnava_ekaadashii_fday].date) else: self.festival_id_to_days[ 'smArta-' + names.get_ekaadashii_name( ekaadashii_paksha, self.daily_panchaangas[d]. lunar_month_sunrise.index) + ' (gRhastha)'].add( self.daily_panchaangas[smaarta_ekaadashii_fday]. date) self.festival_id_to_days[ 'smArta-' + names.get_ekaadashii_name( ekaadashii_paksha, self.daily_panchaangas[d]. lunar_month_sunrise.index) + ' (sannyastha)'].add( self.daily_panchaangas[yati_ekaadashii_fday].date) self.festival_id_to_days[ 'vaiSNava-' + names.get_ekaadashii_name( ekaadashii_paksha, self.daily_panchaangas[d]. lunar_month_sunrise.index)].add( self.daily_panchaangas[ vaishnava_ekaadashii_fday].date) if self.daily_panchaangas[ d].solar_sidereal_date_sunset.month == 9: if ekaadashii_paksha == 'shukla': self.festival_id_to_days[ 'smArta-vaikuNTha-EkAdazI (gRhastha)'].add( self.daily_panchaangas[ smaarta_ekaadashii_fday].date) self.festival_id_to_days[ 'smArta-vaikuNTha-EkAdazI (sannyastha)'].add( self.daily_panchaangas[ yati_ekaadashii_fday].date) self.festival_id_to_days[ 'vaiSNava-vaikuNTha-EkAdazI'].add( self.daily_panchaangas[ vaishnava_ekaadashii_fday].date) if yati_ekaadashii_fday == smaarta_ekaadashii_fday == vaishnava_ekaadashii_fday is None: # Must have already assigned pass else: if self.daily_panchaangas[ d].solar_sidereal_date_sunset.month == 8 and ekaadashii_paksha == 'shukla': # self.add_festival('guruvAyupura-EkAdazI', smaarta_ekaadashii_fday) self.festival_id_to_days['guruvAyupura-EkAdazI'].add( self.daily_panchaangas[vaishnava_ekaadashii_fday]. date) self.festival_id_to_days['kaizika-EkAdazI'].add( self.daily_panchaangas[vaishnava_ekaadashii_fday]. date) # Harivasara Computation if ekaadashii_paksha == 'shukla': def f(x): tp_float = NakshatraDivision( x, ayanaamsha_id=self.ayanaamsha_id ).get_anga_float(zodiac.AngaType.TITHI_PADA) return tp_float - 45 harivasara_end = brentq( f, self.daily_panchaangas[smaarta_ekaadashii_fday]. jd_sunrise - 2, self.daily_panchaangas[smaarta_ekaadashii_fday]. jd_sunrise + 2) else: def f(x): tp_float = NakshatraDivision( x, ayanaamsha_id=self.ayanaamsha_id ).get_anga_float(zodiac.AngaType.TITHI_PADA) return tp_float - 105 harivasara_end = brentq( f, self.daily_panchaangas[smaarta_ekaadashii_fday]. jd_sunrise - 2, self.daily_panchaangas[smaarta_ekaadashii_fday]. jd_sunrise + 2) _date = time.jd_to_utc_gregorian(harivasara_end + (tz_off / 24.0)) _date.set_time_to_day_start() fday_hv = time.utc_gregorian_to_jd( _date) - time.utc_gregorian_to_jd( self.daily_panchaangas[0].date) fest = FestivalInstance(name='harivAsaraH', interval=Interval( jd_start=None, jd_end=harivasara_end)) self.daily_panchaangas[int( fday_hv)].festival_id_to_instance[fest.name] = fest
def write_monthly_tex(panchaanga, template_file, scripts=None, temporal=None): """Write out the panchaanga TeX using a specified template """ if scripts is None: scripts = [sanscript.DEVANAGARI] day_colours = { 0: 'blue', 1: 'blue', 2: 'blue', 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue' } month = { 1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER', 10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER' } MON = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' } WDAY = { 0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat' } monthly_template_file = open( os.path.join(os.path.dirname(__file__), 'templates/monthly_cal_template.tex')) template_lines = template_file.readlines() for i in range(0, len(template_lines) - 3): print(template_lines[i][:-1]) samvatsara_id = (panchaanga.year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = '%s–%s' % ( jyotisha.names.NAMES['SAMVATSARA_NAMES'][scripts[0]][samvatsara_id], jyotisha.names.NAMES['SAMVATSARA_NAMES'][scripts[0]][ (samvatsara_id % 60) + 1]) print('\\mbox{}') print('{\\sffamily\\fontsize{60}{25}\\selectfont %d\\\\[0.5cm]}' % panchaanga.year) print( '\\mbox{\\font\\x="Siddhanta:script=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names) print('\\mbox{\\font\\x="Siddhanta:script=deva" at 32 pt\\x %s } %%' % jyotisha.custom_transliteration.tr('kali', scripts[0])) print('{\\sffamily\\fontsize{32}{25}\\selectfont %d–%d\\\\[0.5cm]}' % (panchaanga.year + 3100, panchaanga.year + 3101)) print( '{\\sffamily\\fontsize{48}{25}\\selectfont \\uppercase{%s}\\\\[0.2cm]}' % panchaanga.city.name) print('{\\sffamily\\fontsize{16}{25}\\selectfont {%s}\\\\[0.5cm]}' % jyotisha.custom_transliteration.print_lat_lon( panchaanga.city.latitude, panchaanga.city.longitude)) print('\\hrule') print('\\newpage') print('\\centering') print('\\centerline{\\LARGE {{%s}}}' % jyotisha.custom_transliteration.tr('mAsAntara-vizESAH', scripts[0])) print('\\begin{multicols*}{3}') print('\\TrickSupertabularIntoMulticols') print( '\\begin{supertabular}' + '{>{\\sffamily}r>{\\sffamily}r>{\\sffamily}c>{\\hangindent=2ex}panchaanga{8cm}}' ) mlast = 1 daily_panchaangas = panchaanga.daily_panchaangas_sorted() for d in range(panchaanga.duration_prior_padding, jyotisha.panchaanga.temporal.MAX_SZ - 1): [y, m, dt, t] = time.jd_to_utc_gregorian(panchaanga.jd_start + d - 1).to_date_fractional_hour_tuple() daily_panchaanga = daily_panchaangas[d] rules_collection = rules.RulesCollection.get_cached(repos_tuple=tuple( panchaanga.computation_system.options.fest_repos)) fest_details_dict = rules_collection.name_to_rule if len(daily_panchaanga.festival_id_to_instance) != 0: if m != mlast: mlast = m print('\\\\') print('%s & %s & %s & {\\raggedright %s} \\\\' % (MON[m], dt, WDAY[daily_panchaanga.date.get_weekday()], '\\\\'.join([ f.tex_code(scripts=scripts, timezone=panchaanga.city.timezone, fest_details_dict=fest_details_dict) for f in sorted( daily_panchaanga.festival_id_to_instance.values()) ]))) if m == 12 and dt == 31: break print('\\end{supertabular}') print('\\end{multicols*}') print('\\renewcommand{\\tamil}[1]{%') print( '{\\fontspec[Scale=0.9,FakeStretch=0.9]{Noto Sans Tamil}\\fontsize{7}{12}\\selectfont #1}}' ) # print('\\clearpage') month_text = '' W6D1 = W6D2 = '' for d in range(panchaanga.duration_prior_padding, jyotisha.panchaanga.temporal.MAX_SZ - 1): [y, m, dt, t] = time.jd_to_utc_gregorian(panchaanga.jd_start + d - 1).to_date_fractional_hour_tuple() # checking @ 6am local - can we do any better? local_time = tz(panchaanga.city.timezone).localize( datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = daily_panchaanga.julian_day_start if dt == 1: currWeek = 1 if m > 1: month_text = month_text.replace('W6D1', W6D1) month_text = month_text.replace('W6D2', W6D2) print(month_text) month_text = W6D1 = W6D2 = '' if currWeek < 6: if daily_panchaanga.date.get_weekday( ) != 0: # Space till Sunday for i in range(daily_panchaanga.date.get_weekday(), 6): print("\\mbox{} & %% %d" % currWeek) print("\\\\ \\hline") print('\\end{tabular}') print('\n\n') # Begin tabular print('\\begin{tabular}{|c|c|c|c|c|c|c|}') print( '\\multicolumn{7}{c}{\\Large \\bfseries \\sffamily %s %s}\\\\[3mm]' % (month[m], y)) print('\\hline') WDAY_NAMES = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] print(' & '.join( ['\\textbf{\\textsf{%s}}' % _day for _day in WDAY_NAMES]) + ' \\\\ \\hline') # Blanks for previous weekdays for i in range(0, daily_panchaanga.date.get_weekday()): if i == 0: month_text += '\n' + ("{W6D1} &") elif i == 1: month_text += '\n' + ("{W6D2} &") else: month_text += '\n' + ("{} &") tithi_data_str = '' for tithi_span in daily_panchaanga.sunrise_day_angas.tithis_with_ends: (tithi_ID, tithi_end_jd) = (tithi_span.anga.index, tithi_span.jd_end) # if tithi_data_str != '': # tithi_data_str += '\\hspace{2ex}' tithi = '\\moon[scale=0.6]{%d}\\hspace{2pt}' % (tithi_ID) + \ jyotisha.names.NAMES['TITHI_NAMES'][scripts[0]][tithi_ID] if tithi_end_jd is None: tithi_data_str = '%s\\mbox{%s\\To{}%s}' % \ (tithi_data_str, tithi, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: tithi_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (tithi_data_str, tithi, Hour(24 * (tithi_end_jd - jd)).toString( format=panchaanga.fmt), '\\hspace{2ex}') nakshatra_data_str = '' for nakshatra_span in daily_panchaanga.sunrise_day_angas.nakshatras_with_ends: (nakshatra_ID, nakshatra_end_jd) = (nakshatra_span.anga.index, nakshatra_span.jd_end) # if nakshatra_data_str != '': # nakshatra_data_str += '\\hspace{2ex}' nakshatra = jyotisha.names.NAMES['NAKSHATRA_NAMES'][ scripts[0]][nakshatra_ID] if nakshatra_end_jd is None: nakshatra_data_str = '%s\\mbox{%s\\To{}%s}' % \ (nakshatra_data_str, nakshatra, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: nakshatra_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (nakshatra_data_str, nakshatra, Hour(24 * (nakshatra_end_jd - jd)).toString(format=panchaanga.fmt), '\\hspace{2ex}') yoga_data_str = '' for yoga_span in daily_panchaanga.sunrise_day_angas.yogas_with_ends: (yoga_ID, yoga_end_jd) = (yoga_span.anga.index, yoga_span.jd_end) # if yoga_data_str != '': # yoga_data_str += '\\hspace{2ex}' yoga = jyotisha.names.NAMES['YOGA_NAMES'][scripts[0]][yoga_ID] if yoga_end_jd is None: yoga_data_str = '%s\\mbox{%s\\To{}%s}' % \ (yoga_data_str, yoga, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: yoga_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (yoga_data_str, yoga, Hour(24 * (yoga_end_jd - jd)).toString( format=panchaanga.fmt), '\\hspace{2ex}') karana_data_str = '' for numKaranam, karaNa_span in enumerate( daily_panchaanga.sunrise_day_angas.karanas_with_ends): (karana_ID, karana_end_jd) = (karaNa_span.anga.index, karaNa_span.jd_end) # if numKaranam == 1: # karana_data_str += '\\hspace{2ex}' if numKaranam == 2: karana_data_str = karana_data_str + '\\\\' karana = jyotisha.names.NAMES['KARANA_NAMES'][ scripts[0]][karana_ID] if karana_end_jd is None: karana_data_str = '%s\\mbox{%s\\To{}%s}' % \ (karana_data_str, karana, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: karana_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (karana_data_str, karana, Hour(24 * (karana_end_jd - jd)).toString(format=panchaanga.fmt), '\\hspace{2ex}') sunrise = Hour(24 * (daily_panchaanga.jd_sunrise - jd)).toString( format=panchaanga.fmt) sunset = Hour(24 * (daily_panchaanga.jd_sunset - jd)).toString( format=panchaanga.fmt) saangava = Hour( 24 * (daily_panchaanga.day_length_based_periods.saangava.jd_start - jd)).toString(format=panchaanga.fmt) rahu = '%s--%s' % ( Hour(24 * (daily_panchaanga.day_length_based_periods.raahu.jd_start - jd)).toString(format=panchaanga.fmt), Hour(24 * (daily_panchaanga.day_length_based_periods.raahu.jd_end - jd)).toString(format=panchaanga.fmt)) yama = '%s--%s' % ( Hour(24 * (daily_panchaanga.day_length_based_periods.yama.jd_start - jd)).toString(format=panchaanga.fmt), Hour(24 * (daily_panchaanga.day_length_based_periods.yama.jd_end - jd)).toString(format=panchaanga.fmt)) if daily_panchaanga.solar_sidereal_date_sunset.month_transition is None: month_end_str = '' else: _m = daily_panchaangas[d - 1].solar_sidereal_date_sunset.month if daily_panchaanga.solar_sidereal_date_sunset.month_transition >= daily_panchaangas[ d + 1].jd_sunrise: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][_m], Hour(24 * (daily_panchaanga.solar_sidereal_date_sunset. month_transition - daily_panchaangas[d + 1].julian_day_start)).toString( format=panchaanga.fmt)) else: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][_m], Hour(24 * (daily_panchaanga.solar_sidereal_date_sunset. month_transition - daily_panchaanga.julian_day_start) ).toString(format=panchaanga.fmt)) month_data = '\\sunmonth{%s}{%d}{%s}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][ daily_panchaanga.solar_sidereal_date_sunset.month], daily_panchaanga.solar_sidereal_date_sunset.day, month_end_str) if currWeek < 6: month_text += '\n' + ( '\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[daily_panchaanga.date.get_weekday()], dt, month_data, jyotisha.names.get_chandra_masa( daily_panchaanga.lunar_month_sunrise, jyotisha.names.NAMES, scripts[0]))) month_text += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, saangava)) month_text += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatra_data_str, yoga_data_str, karana_data_str)) month_text += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! month_text += '\n' + ('{%s}' % '\\eventsep '.join([ f.tex_code(scripts=scripts, timezone=panchaanga.city.timezone, fest_details_dict=fest_details_dict) for f in sorted(daily_panchaanga.festival_id_to_instance.values()) ])) else: if daily_panchaanga.date.get_weekday() == 0: W6D1 = '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[daily_panchaanga.date.get_weekday( )], dt, month_data, jyotisha.names.get_chandra_masa( daily_panchaanga.lunar_month_sunrise, jyotisha.names.NAMES, scripts[0]))) W6D1 += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, saangava)) W6D1 += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatra_data_str, yoga_data_str, karana_data_str)) W6D1 += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! W6D1 += '\n' + ('{%s}' % '\\eventsep '.join([ f.tex_code(scripts=scripts, timezone=Timezone(panchaanga.city.timezone), fest_details_dict=fest_details_dict) for f in sorted(daily_panchaanga.festival_id_to_instance.values()) ])) elif daily_panchaanga.date.get_weekday() == 1: W6D2 = '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[daily_panchaanga.date.get_weekday( )], dt, month_data, jyotisha.names.get_chandra_masa( daily_panchaanga.lunar_month_sunrise, jyotisha.names.NAMES, scripts[0]))) W6D2 += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, saangava)) W6D2 += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatra_data_str, yoga_data_str, karana_data_str)) W6D2 += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! W6D2 += '\n' + ('{%s}' % '\\eventsep '.join([ f.tex_code(scripts=scripts, timezone=panchaanga.city.timezone, fest_details_dict=fest_details_dict) for f in sorted(daily_panchaanga.festival_id_to_instance.values()) ])) else: # Cannot be here, since we cannot have more than 2 days in week 6 of any month! pass if daily_panchaanga.date.get_weekday() == 6: month_text += '\n' + ("\\\\ \\hline %%END OF WEEK %d" % (currWeek)) currWeek += 1 else: if currWeek < 6: month_text += '\n' + ("&") if m == 12 and dt == 31: break month_text = month_text.replace('W6D1', W6D1) month_text = month_text.replace('W6D2', W6D2) print(month_text) if currWeek < 6: for i in range(daily_panchaanga.date.get_weekday() + 1, 6): print("{} &") if daily_panchaanga.date.get_weekday() != 6: print("\\\\ \\hline") print('\\end{tabular}') print('\n\n') print(template_lines[-2][:-1]) print(template_lines[-1][:-1])
def set_datetime_given_tz(self, local_time, tzone): float_tzone = self.translate_seconds_to_float_time(datetime.utcoffset(tzone).seconds) utc_time = local_time - float_tzone return utc_time
def emit(panchaanga, time_format="hh:mm", scripts=None, output_stream=None): """Write out the panchaanga TeX using a specified template """ # day_colours = {0: 'blue', 1: 'blue', 2: 'blue', # 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue'} compute_lagnams = panchaanga.computation_system.options.set_lagnas if scripts is None: scripts = [sanscript.DEVANAGARI] month = {1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER', 10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER'} WDAY = {0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat'} template_file = open(os.path.join(os.path.dirname(__file__), 'templates/daily_cal_template.tex')) template_lines = template_file.readlines() for i in range(len(template_lines)): print(template_lines[i][:-1], file=output_stream) year = panchaanga.start_date.year logging.debug(year) samvatsara_id = (year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = (jyotisha.names.NAMES['SAMVATSARA_NAMES'][scripts[0]][samvatsara_id], jyotisha.names.NAMES['SAMVATSARA_NAMES'][scripts[0]][(samvatsara_id % 60) + 1]) yname = samvatsara_names[0] # Assign year name until Mesha Sankranti print('\\mbox{}', file=output_stream) print('\\renewcommand{\\yearname}{%d}' % year, file=output_stream) print('\\begin{center}', file=output_stream) print('{\\sffamily \\fontsize{80}{80}\\selectfont %d\\\\[0.5cm]}' % year, file=output_stream) print('\\mbox{\\fontsize{48}{48}\\selectfont %s–%s}\\\\' % samvatsara_names, file=output_stream) print('\\mbox{\\fontsize{32}{32}\\selectfont %s } %%' % jyotisha.custom_transliteration.tr('kali', scripts[0]), file=output_stream) print('{\\sffamily \\fontsize{43}{43}\\selectfont %d–%d\\\\[0.5cm]}\n\\hrule\n\\vspace{0.2cm}' % (year + 3100, year + 3101), file=output_stream) print('{\\sffamily \\fontsize{50}{50}\\selectfont \\uppercase{%s}\\\\[0.2cm]}' % panchaanga.city.name, file=output_stream) print('{\\sffamily \\fontsize{23}{23}\\selectfont {%s}\\\\[0.2cm]}' % jyotisha.custom_transliteration.print_lat_lon(panchaanga.city.latitude, panchaanga.city.longitude), file=output_stream) print('\\hrule', file=output_stream) print('\\end{center}', file=output_stream) print('\\clearpage\\pagestyle{fancy}', file=output_stream) daily_panchaangas = panchaanga.daily_panchaangas_sorted() for d, daily_panchaanga in enumerate(daily_panchaangas): if daily_panchaanga.date < panchaanga.start_date or daily_panchaanga.date > panchaanga.end_date: continue [y, m, dt] = [daily_panchaanga.date.year, daily_panchaanga.date.month, daily_panchaanga.date.day] # checking @ 6am local - can we do any better? local_time = tz(panchaanga.city.timezone).localize(datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = daily_panchaanga.julian_day_start tithi_data_str = '' for iTithi, tithi_span in enumerate(daily_panchaanga.sunrise_day_angas.tithis_with_ends): (tithi_ID, tithi_end_jd) = (tithi_span.anga.index, tithi_span.jd_end) # if tithi_data_str != '': # tithi_data_str += '\\hspace{1ex}' tithi = '\\raisebox{-1pt}{\\moon[scale=0.8]{%d}}\\hspace{2pt}' % (tithi_ID) + \ jyotisha.names.NAMES['TITHI_NAMES'][scripts[0]][tithi_ID] if tithi_end_jd is None: if iTithi == 0: tithi_data_str = '%s\\mbox{%s\\To{}%s}' % \ (tithi_data_str, tithi, jyotisha.custom_transliteration.tr('ahOrAtram (tridinaspRk)', scripts[0])) else: tithi_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}\\hspace{1ex}' % \ (tithi_data_str, tithi, time.Hour( 24 * (tithi_end_jd - daily_panchaanga.jd_sunrise)).toString(format='gg-pp'), time.Hour(24 * (tithi_end_jd - jd)).toString( format=time_format)) nakshatra_data_str = '' for iNakshatra, nakshatra_span in enumerate(daily_panchaanga.sunrise_day_angas.nakshatras_with_ends): (nakshatra_ID, nakshatra_end_jd) = (nakshatra_span.anga.index, nakshatra_span.jd_end) if nakshatra_data_str != '': nakshatra_data_str += '\\hspace{1ex}' nakshatra = jyotisha.names.NAMES['NAKSHATRA_NAMES'][scripts[0]][nakshatra_ID] if nakshatra_end_jd is None: if iNakshatra == 0: nakshatra_data_str = '%s\\mbox{%s\\To{}%s}' % \ (nakshatra_data_str, nakshatra, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: nakshatra_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}' % \ (nakshatra_data_str, nakshatra, time.Hour( 24 * (nakshatra_end_jd - daily_panchaanga.jd_sunrise)).toString(format='gg-pp'), time.Hour(24 * (nakshatra_end_jd - jd)).toString( format=time_format)) rashi_data_str = '' for iRaashi, raashi_span in enumerate(daily_panchaanga.sunrise_day_angas.raashis_with_ends): if iRaashi == 0: (rashi_ID, rashi_end_jd) = (raashi_span.anga.index, raashi_span.jd_end) # if rashi_data_str != '': # rashi_data_str += '\\hspace{1ex}' rashi = jyotisha.names.NAMES['RASHI_SUFFIXED_NAMES'][scripts[0]][rashi_ID] if rashi_end_jd is None: rashi_data_str = '%s\\mbox{%s}' % (rashi_data_str, rashi) else: rashi_data_str = '%s\\mbox{%s \\RIGHTarrow \\textsf{%s}}' % \ (rashi_data_str, rashi, time.Hour(24 * (rashi_end_jd - jd)).toString( format=time_format)) if compute_lagnams: lagna_data_str = 'लग्नम्–' for lagna_ID, lagna_end_jd in daily_panchaanga.lagna_data: lagna = jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][lagna_ID] lagna_data_str = '%s\\mbox{%s\\RIGHTarrow\\textsf{%s}} ' % \ (lagna_data_str, lagna, time.Hour(24 * (lagna_end_jd - jd)).toString( format=time_format)) yoga_data_str = '' for iYoga, yoga_span in enumerate(daily_panchaanga.sunrise_day_angas.yogas_with_ends): (yoga_ID, yoga_end_jd) = (yoga_span.anga.index, yoga_span.jd_end) # if yoga_data_str != '': # yoga_data_str += '\\hspace{1ex}' yoga = jyotisha.names.NAMES['YOGA_NAMES'][scripts[0]][yoga_ID] if yoga_end_jd is None: if iYoga == 0: yoga_data_str = '%s\\mbox{%s\\To{}%s}' % \ (yoga_data_str, yoga, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: yoga_data_str = '%s\\mbox{%s\\Too{}}' % \ (yoga_data_str, yoga) else: yoga_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}\\hspace{1ex}' % \ (yoga_data_str, yoga, time.Hour(24 * (yoga_end_jd - daily_panchaanga.jd_sunrise)).toString( format='gg-pp'), time.Hour(24 * (yoga_end_jd - jd)).toString( format=time_format)) if yoga_end_jd is not None: yoga_data_str += '\\mbox{%s\\Too{}}' % ( jyotisha.names.NAMES['YOGA_NAMES'][scripts[0]][(yoga_ID % 27) + 1]) karana_data_str = '' for numKaranam, karaNa_span in enumerate(daily_panchaanga.sunrise_day_angas.karanas_with_ends): (karana_ID, karana_end_jd) = (karaNa_span.anga.index, karaNa_span.jd_end) # if numKaranam == 1: # karana_data_str += '\\hspace{1ex}' karana = jyotisha.names.NAMES['KARANA_NAMES'][scripts[0]][karana_ID] if karana_end_jd is None: karana_data_str = '%s\\mbox{%s\\Too{}}' % \ (karana_data_str, karana) else: karana_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}\\hspace{1ex}' % \ (karana_data_str, karana, time.Hour( 24 * (karana_end_jd - daily_panchaanga.jd_sunrise)).toString(format='gg-pp'), time.Hour(24 * (karana_end_jd - jd)).toString( format=time_format)) sunrise = time.Hour(24 * (daily_panchaanga.jd_sunrise - jd)).toString( format=time_format) sunset = time.Hour(24 * (daily_panchaanga.jd_sunset - jd)).toString(format=time_format) moonrise = time.Hour(24 * (daily_panchaanga.jd_moonrise - jd)).toString( format=time_format) moonset = time.Hour(24 * (daily_panchaanga.jd_moonset - jd)).toString( format=time_format) braahma_start = time.Hour(24 * (daily_panchaanga.day_length_based_periods.braahma.jd_start - jd)).toString( format=time_format) praatahsandhya_start = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.praatas_sandhyaa.jd_start - jd)).toString(format=time_format) praatahsandhya_end = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.praatas_sandhyaa_end.jd_start - jd)).toString(format=time_format) saangava = time.Hour(24 * (daily_panchaanga.day_length_based_periods.saangava.jd_start - jd)).toString( format=time_format) madhyaahna = time.Hour(24 * (daily_panchaanga.day_length_based_periods.madhyaahna.jd_start - jd)).toString( format=time_format) madhyahnika_sandhya_start = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.maadhyaahnika_sandhyaa.jd_start - jd)).toString(format=time_format) madhyahnika_sandhya_end = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.maadhyaahnika_sandhyaa_end.jd_start - jd)).toString(format=time_format) aparaahna_muhuurta = time.Hour(24 * (daily_panchaanga.day_length_based_periods.aparaahna_muhuurta.jd_start - jd)).toString( format=time_format) sayahna = time.Hour(24 * (daily_panchaanga.day_length_based_periods.saayaahna.jd_start - jd)).toString( format=time_format) sayamsandhya_start = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.saayam_sandhyaa.jd_start - jd)).toString(format=time_format) sayamsandhya_end = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.pradosha.jd_end - jd)).toString(format=time_format) ratriyama1 = time.Hour(24 * (daily_panchaanga.day_length_based_periods.raatri_yaama_1.jd_start - jd)).toString( format=time_format) shayana_time_end = time.Hour(24 * (daily_panchaanga.day_length_based_periods.shayana.jd_start - jd)).toString( format=time_format) dinaanta = time.Hour(24 * (daily_panchaanga.day_length_based_periods.dinaanta.jd_start - jd)).toString( format=time_format) rahu = '%s--%s' % ( time.Hour(24 * (daily_panchaanga.day_length_based_periods.raahu.jd_start - jd)).toString( format=time_format), time.Hour(24 * (daily_panchaanga.day_length_based_periods.raahu.jd_end - jd)).toString( format=time_format)) yama = '%s--%s' % ( time.Hour(24 * (daily_panchaanga.day_length_based_periods.yama.jd_start - jd)).toString( format=time_format), time.Hour(24 * (daily_panchaanga.day_length_based_periods.yama.jd_end - jd)).toString( format=time_format)) gulika = '%s--%s' % ( time.Hour(24 * (daily_panchaanga.day_length_based_periods.gulika.jd_start - jd)).toString( format=time_format), time.Hour(24 * (daily_panchaanga.day_length_based_periods.gulika.jd_end - jd)).toString( format=time_format)) if daily_panchaanga.solar_sidereal_date_sunset.month == 1: # Flip the year name for the remaining days yname = samvatsara_names[1] # Assign samvatsara, ayana, rtu # sar_data = '{%s}{%s}{%s}' % (yname, jyotisha.names.NAMES['AYANA_NAMES'][scripts[0]][daily_panchaanga.solar_sidereal_date_sunset.month], jyotisha.names.NAMES['RTU_NAMES'][scripts[0]][daily_panchaanga.solar_sidereal_date_sunset.month]) if daily_panchaanga.solar_sidereal_date_sunset.month_transition is None: month_end_str = '' else: _m = daily_panchaangas[d - 1].solar_sidereal_date_sunset.month if daily_panchaanga.solar_sidereal_date_sunset.month_transition >= daily_panchaangas[d + 1].jd_sunrise: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][_m], time.Hour( 24 * (daily_panchaanga.solar_sidereal_date_sunset.month_transition - daily_panchaangas[d + 1].julian_day_start)).toString(format=time_format)) else: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][_m], time.Hour( 24 * (daily_panchaanga.solar_sidereal_date_sunset.month_transition - daily_panchaanga.julian_day_start)).toString(format=time_format)) month_data = '\\sunmonth{%s}{%d}{%s}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][daily_panchaanga.solar_sidereal_date_sunset.month], daily_panchaanga.solar_sidereal_date_sunset.day, month_end_str) print('\\caldata{%s}{%s}{%s{%s}{%s}{%s}%s}' % (month[m], dt, month_data, jyotisha.names.get_chandra_masa(daily_panchaanga.lunar_month_sunrise.index, jyotisha.names.NAMES, scripts[0]), jyotisha.names.NAMES['RTU_NAMES'][scripts[0]][int(ceil(daily_panchaanga.lunar_month_sunrise.index))], jyotisha.names.NAMES['VARA_NAMES'][scripts[0]][daily_panchaanga.date.get_weekday()], sar_data), file=output_stream) if daily_panchaanga.jd_moonrise > daily_panchaangas[d + 1].jd_sunrise: moonrise = '---' if daily_panchaanga.jd_moonset > daily_panchaangas[d + 1].jd_sunrise: moonset = '---' if daily_panchaanga.jd_moonrise < daily_panchaanga.jd_moonset: print('{\\sunmoonrsdata{%s}{%s}{%s}{%s}' % (sunrise, sunset, moonrise, moonset), file=output_stream) else: print('{\\sunmoonsrdata{%s}{%s}{%s}{%s}' % (sunrise, sunset, moonrise, moonset), file=output_stream) print( '{\\kalas{%s %s %s %s %s %s %s %s %s %s %s %s %s %s}}}' % (braahma_start, praatahsandhya_start, praatahsandhya_end, saangava, madhyahnika_sandhya_start, madhyahnika_sandhya_end, madhyaahna, aparaahna_muhuurta, sayahna, sayamsandhya_start, sayamsandhya_end, ratriyama1, shayana_time_end, dinaanta), file=output_stream) if compute_lagnams: print('{\\tnykdata{%s}%%\n{%s}{%s}%%\n{%s}%%\n{%s}{%s}\n}' % (tithi_data_str, nakshatra_data_str, rashi_data_str, yoga_data_str, karana_data_str, lagna_data_str), file=output_stream) else: print('{\\tnykdata{%s}%%\n{%s}{%s}%%\n{%s}%%\n{%s}{\\scriptsize %s}\n}' % (tithi_data_str, nakshatra_data_str, rashi_data_str, yoga_data_str, karana_data_str, ''), file=output_stream) rules_collection = rules.RulesCollection.get_cached( repos_tuple=tuple(panchaanga.computation_system.options.fest_repos)) fest_details_dict = rules_collection.name_to_rule # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! print('{%s}' % '\\eventsep '.join( [f.tex_code(scripts=scripts, timezone=Timezone(timezone_id=panchaanga.city.timezone), fest_details_dict=fest_details_dict) for f in sorted(daily_panchaanga.festival_id_to_instance.values())]), file=output_stream) print('{%s} ' % WDAY[daily_panchaanga.date.get_weekday()], file=output_stream) print('\\cfoot{\\rygdata{%s}{%s}{%s}}' % (rahu, yama, gulika), file=output_stream) if m == 12 and dt == 31: break print('\\end{document}', file=output_stream)
def write_monthly_tex(panchaanga, time_format="hh:mm", languages=None, scripts=None): """Write out the panchaanga TeX using a specified template """ if scripts is None: scripts = [sanscript.DEVANAGARI] day_colours = {0: 'blue', 1: 'blue', 2: 'blue', 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue'} if languages is None: languages = ["sa"] monthly_template_file = open(os.path.join(os.path.dirname(__file__), 'templates/monthly_cal_template.tex')) template_lines = monthly_template_file.readlines() for i in range(0, len(template_lines) - 3): print(template_lines[i][:-1]) samvatsara_id = (panchaanga.year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = '%s–%s' % (names.NAMES['SAMVATSARA_NAMES']['sa'][scripts[0]][samvatsara_id], names.NAMES['SAMVATSARA_NAMES']['sa'][scripts[0]][(samvatsara_id % 60) + 1]) print('\\mbox{}') print('{\\sffamily\\fontsize{60}{25}\\selectfont %d\\\\[0.5cm]}' % panchaanga.year) print('\\mbox{\\font\\x="Siddhanta:language=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names) print('\\mbox{\\font\\x="Siddhanta:language=deva" at 32 pt\\x %s } %%' % jyotisha.custom_transliteration.tr('kali', scripts[0])) print('{\\sffamily\\fontsize{32}{25}\\selectfont %d–%d\\\\[0.5cm]}' % (panchaanga.year + 3100, panchaanga.year + 3101)) print('{\\sffamily\\fontsize{48}{25}\\selectfont \\uppercase{%s}\\\\[0.2cm]}' % panchaanga.city.name) print('{\\sffamily\\fontsize{16}{25}\\selectfont {%s}\\\\[0.5cm]}' % jyotisha.custom_transliteration.print_lat_lon(panchaanga.city.latitude, panchaanga.city.longitude)) print('\\hrule') print('\\newpage') print('\\centering') print('\\centerline{\\LARGE {{%s}}}' % jyotisha.custom_transliteration.tr('mAsAntara-vizESAH', scripts[0])) print('\\begin{multicols*}{3}') print('\\TrickSupertabularIntoMulticols') print('\\begin{supertabular}' + '{>{\\sffamily}r>{\\sffamily}r>{\\sffamily}c>{\\hangindent=2ex}p{8cm}}') mlast = 1 daily_panchaangas = panchaanga.daily_panchaangas_sorted() for d in range(panchaanga.duration_prior_padding, jyotisha.panchaanga.temporal.MAX_SZ - 1): [y, m, dt, t] = time.jd_to_utc_gregorian(panchaanga.jd_start + d - 1).to_date_fractional_hour_tuple() daily_panchaanga = daily_panchaangas[d] rules_collection = rules.RulesCollection.get_cached( repos_tuple=tuple(panchaanga.computation_system.festival_options.repos), julian_handling=panchaanga.computation_system.festival_options.julian_handling) fest_details_dict = rules_collection.name_to_rule if len(daily_panchaanga.festival_id_to_instance) != 0: if m != mlast: mlast = m print('\\\\') print('%s & %s & %s & {\\raggedright %s} \\\\' % (names.month_map[m], dt, names.weekday_short_map[daily_panchaanga.date.get_weekday()], '\\\\'.join([f.tex_code(languages=languages, scripts=scripts, timezone=panchaanga.city.timezone, fest_details_dict=fest_details_dict, reference_date=daily_panchaanga.date) for f in sorted(daily_panchaanga.festival_id_to_instance.values())]))) if m == 12 and dt == 31: break print('\\end{supertabular}') print('\\end{multicols*}') print('\\renewcommand{\\tamil}[1]{%') print('{\\fontspec[Scale=0.9,FakeStretch=0.9]{Noto Sans Tamil}\\fontsize{7}{12}\\selectfont #1}}') # print('\\clearpage') month_text = '' W6D1 = W6D2 = '' for d in range(panchaanga.duration_prior_padding, jyotisha.panchaanga.temporal.MAX_SZ - 1): [y, m, dt, t] = time.jd_to_utc_gregorian(panchaanga.jd_start + d - 1).to_date_fractional_hour_tuple() # checking @ 6am local - can we do any better? local_time = tz(panchaanga.city.timezone).localize(datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = daily_panchaanga.julian_day_start if dt == 1: currWeek = 1 if m > 1: month_text = month_text.replace('W6D1', W6D1) month_text = month_text.replace('W6D2', W6D2) print(month_text) month_text = W6D1 = W6D2 = '' if currWeek < 6: if daily_panchaanga.date.get_weekday() != 0: # Space till Sunday for i in range(daily_panchaanga.date.get_weekday(), 6): print("\\mbox{} & %% %d" % currWeek) print("\\\\ \\hline") print('\\end{tabular}') print('\n\n') # Begin tabular print('\\begin{tabular}{|c|c|c|c|c|c|c|}') print('\\multicolumn{7}{c}{\\Large \\bfseries \\sffamily %s %s}\\\\[3mm]' % ( names.month_map[m], y)) print('\\hline') WDAY_NAMES = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] print(' & '.join(['\\textbf{\\textsf{%s}}' % _day for _day in WDAY_NAMES]) + ' \\\\ \\hline') # Blanks for previous weekdays for i in range(0, daily_panchaanga.date.get_weekday()): if i == 0: month_text += '\n' + ("{W6D1} &") elif i == 1: month_text += '\n' + ("{W6D2} &") else: month_text += '\n' + ("{} &") tithi_data_str = day_details.get_tithi_data_str(daily_panchaanga, scripts, time_format) nakshatra_data_str = day_details.get_nakshatra_data_str(daily_panchaanga, scripts, time_format) yoga_data_str = day_details.get_yoga_data_str(daily_panchaanga, scripts, time_format) karana_data_str = day_details.get_karaNa_data_str(daily_panchaanga, scripts, time_format) sunrise = Hour(24 * (daily_panchaanga.jd_sunrise - jd)).to_string( format=time_format) sunset = Hour(24 * (daily_panchaanga.jd_sunset - jd)).to_string(format=time_format) saangava = Hour(24 * (daily_panchaanga.day_length_based_periods.fifteen_fold_division.saangava.jd_start - jd)).to_string( format=time_format) rahu = '%s--%s' % ( Hour(24 * (daily_panchaanga.day_length_based_periods.eight_fold_division.raahu.jd_start - jd)).to_string( format=time_format), Hour(24 * (daily_panchaanga.day_length_based_periods.eight_fold_division.raahu.jd_end - jd)).to_string( format=time_format)) yama = '%s--%s' % ( Hour(24 * (daily_panchaanga.day_length_based_periods.eight_fold_division.yama.jd_start - jd)).to_string( format=time_format), Hour(24 * (daily_panchaanga.day_length_based_periods.eight_fold_division.yama.jd_end - jd)).to_string( format=time_format)) if daily_panchaanga.solar_sidereal_date_sunset.month_transition is None: month_end_str = '' else: _m = daily_panchaangas[d - 1].solar_sidereal_date_sunset.month if daily_panchaanga.solar_sidereal_date_sunset.month_transition >= daily_panchaangas[d + 1].jd_sunrise: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( names.NAMES['RASHI_NAMES']['sa'][scripts[0]][_m], Hour( 24 * (daily_panchaanga.solar_sidereal_date_sunset.month_transition - daily_panchaangas[d + 1].julian_day_start)).to_string(format=time_format)) else: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( names.NAMES['RASHI_NAMES']['sa'][scripts[0]][_m], Hour( 24 * (daily_panchaanga.solar_sidereal_date_sunset.month_transition - daily_panchaanga.julian_day_start)).to_string(format=time_format)) month_data = '\\sunmonth{%s}{%d}{%s}' % ( names.NAMES['RASHI_NAMES']['sa'][scripts[0]][daily_panchaanga.solar_sidereal_date_sunset.month], daily_panchaanga.solar_sidereal_date_sunset.day, month_end_str) if currWeek < 6: month_text += '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[daily_panchaanga.date.get_weekday()], dt, month_data, names.get_chandra_masa(daily_panchaanga.lunar_month_sunrise, scripts[0]))) month_text += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, saangava)) month_text += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatra_data_str, yoga_data_str, karana_data_str)) month_text += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! month_text += '\n' + ('{%s}' % '\\eventsep '.join( [f.tex_code(languages=languages, scripts=scripts, timezone=panchaanga.city.timezone, fest_details_dict=fest_details_dict, reference_date=daily_panchaanga.date) for f in sorted(daily_panchaanga.festival_id_to_instance.values())])) else: if daily_panchaanga.date.get_weekday() == 0: W6D1 = '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[daily_panchaanga.date.get_weekday()], dt, month_data, names.get_chandra_masa(daily_panchaanga.lunar_month_sunrise,scripts[0]))) W6D1 += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, saangava)) W6D1 += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatra_data_str, yoga_data_str, karana_data_str)) W6D1 += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! W6D1 += '\n' + ('{%s}' % '\\eventsep '.join( [f.tex_code(languages=languages, scripts=scripts, timezone=Timezone(panchaanga.city.timezone), fest_details_dict=fest_details_dict, reference_date=daily_panchaanga.date) for f in sorted(daily_panchaanga.festival_id_to_instance.values())])) elif daily_panchaanga.date.get_weekday() == 1: W6D2 = '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[daily_panchaanga.date.get_weekday()], dt, month_data, names.get_chandra_masa(daily_panchaanga.lunar_month_sunrise,scripts[0]))) W6D2 += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, saangava)) W6D2 += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatra_data_str, yoga_data_str, karana_data_str)) W6D2 += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! W6D2 += '\n' + ('{%s}' % '\\eventsep '.join( [f.tex_code(languages=languages, scripts=scripts, timezone=panchaanga.city.timezone, fest_details_dict=fest_details_dict, reference_date=daily_panchaanga.date) for f in sorted(daily_panchaanga.festival_id_to_instance.values())])) else: # Cannot be here, since we cannot have more than 2 days in week 6 of any month! pass if daily_panchaanga.date.get_weekday() == 6: month_text += '\n' + ("\\\\ \\hline %%END OF WEEK %d" % (currWeek)) currWeek += 1 else: if currWeek < 6: month_text += '\n' + ("&") if m == 12 and dt == 31: break month_text = month_text.replace('W6D1', W6D1) month_text = month_text.replace('W6D2', W6D2) print(month_text) if currWeek < 6: for i in range(daily_panchaanga.date.get_weekday() + 1, 6): print("{} &") if daily_panchaanga.date.get_weekday() != 6: print("\\\\ \\hline") print('\\end{tabular}') print('\n\n') print(template_lines[-2][:-1]) print(template_lines[-1][:-1])
def validate_is_utc(start_date_time: datetime) -> None: """Validate that start_date_time is always UTC for consistency.""" if datetime.utcoffset(start_date_time) == timedelta(0): return None raise ValidationError(_("%(start_date_time)s is not set to the UTC"))
def set_schedule(dep_place, arr_place, home_sleep_time, home_wake_time, events_list, days): # Defining home and local time zones dep_zone = timezone(dep_place) arr_zone = timezone(arr_place) # Defining the sleeping time and the wake up time dep_sleep_time = datetime.strptime(home_sleep_time, "%d/%m/%Y %H:%M") dep_sleep_time = dep_zone.localize(dep_sleep_time) dep_wake_time = datetime.strptime(home_wake_time, "%d/%m/%Y %H:%M") dep_wake_time = dep_zone.localize(dep_wake_time) local_sleep_time = datetime.astimezone(dep_sleep_time, arr_zone) local_wake_time = datetime.astimezone(dep_wake_time, arr_zone) # Other parameters and work variables time_list = [] # Difference between the time zones diff_zone = datetime.utcoffset(local_sleep_time) - datetime.utcoffset( dep_sleep_time) if diff_zone > timedelta(days=0, hours=0, minutes=0): direction = 'east' else: direction = 'west' diff_zone = abs(diff_zone) # Inserting the day 0 in the list: the user is still at home time_list.append({ "sleep_time": dep_sleep_time.strftime("%d/%m/%Y %H:%M"), "wake_time": dep_wake_time.strftime("%d/%m/%Y %H:%M") }) # Computing the sleeping time schedule i = 0 while i < days: # Controlling the travel direction if direction == 'east': local_sleep_time = local_sleep_time - diff_zone / days local_wake_time = local_wake_time - diff_zone / days elif direction == 'west': local_sleep_time = local_sleep_time + diff_zone / days local_wake_time = local_wake_time + diff_zone / days wake_time = local_wake_time sleep_time = local_sleep_time # Adapting the schedule to the appointments of the user for x in events_list: start_time = datetime.strptime(x["start_time"], "%d/%m/%Y %H:%M") start_time = arr_zone.localize(start_time) if sleep_time < start_time < wake_time: # Start the procedure for anticipating the alarm clock # Set the alarm 1 hour before the beginning of the event local_wake_time = start_time - timedelta(hours=1) local_sleep_time = local_wake_time - timedelta(hours=7) # mySleep = myWake - (dep_wake_time - dep_sleep_time) break # Writing the list with the sleeping schedule time_list.append({ "sleep_time": local_sleep_time.strftime("%d/%m/%Y %H:%M"), "wake_time": local_wake_time.strftime("%d/%m/%Y %H:%M") }) local_sleep_time = local_sleep_time + timedelta(days=1) local_wake_time = local_wake_time + timedelta(days=1) i += 1 return time_list
def utcoffset(self): """Returns our offset from UTC, including any leap-second adjustments.""" return datetime.utcoffset(self) + timedelta(seconds=self.__leapseconds(self.tzinfo))
def getTodayEventsById(self, cr, uid, ids, params, timeDtFrmt, context=None): """ Plan tasks after drag&drop task on planning :param cr: database cursor :param uid: current user id :param ids: list of ids :param params: contains start_working_time : date/heure début de journée travaillée end_working_time : date/heure fin de journée start_lunch_time : date/heure début pause déjeuner end_lunch_time : date/heure fin pause déjeuner start_dt: date/heure du début de la plage souhaitée type : string key : 'officer', 'team', 'partner' calendar_id : celui de l'agent / ou celui de l'équipe, selon le type This method is used to get events on start_dt (lunch including) for officer or team (calendar_id) """ if not set( ('start_working_time', 'end_working_time', 'start_lunch_time', 'end_lunch_time', 'start_dt', 'calendar_id')).issubset(params): raise Exception( 'Erreur : il manque des paramètres pour pouvoir planifier (Heure d' 'embauche, heure de déjeuner...) \n Veuillez contacter votre administrateur ' ) #Date format passed by javascript client : date from utc. #Client swif lose the timezone because of the serialisation in JSON request (JSON.stringify) timeDtFrmtWithTmz = "%Y-%m-%dT%H:%M:%S.000Z" #Get user context context_tz = self.pool.get('res.users').read( cr, uid, [uid], ['context_tz'])[0]['context_tz'] or 'Europe/Paris' tzinfo = pytz.timezone(context_tz) events = [] todayDt = datetime.now(tzinfo) #Calculate time differencee between utc and user's timezone deltaTz = int((datetime.utcoffset(todayDt).total_seconds()) / 3600) #Get Start and end working time, lunch start and stop times start_dt = datetime.strptime(params['start_dt'], timeDtFrmtWithTmz) start_working_time = start_dt.replace( hour=(int(params['start_working_time']) - deltaTz), minute=0, second=0, microsecond=0) start_lunch_time = start_dt.replace( hour=(int(params['start_lunch_time']) - deltaTz), minute=0, second=0, microsecond=0) end_lunch_time = start_dt.replace(hour=(int(params['end_lunch_time']) - deltaTz), minute=0, second=0, microsecond=0) #Add in list events.append({ 'title': "lunchTime", 'date_start': start_lunch_time, 'date_end': end_lunch_time }) end_working_time = start_dt.replace( hour=(int(params['end_working_time']) - deltaTz), minute=0, second=0, microsecond=0) events.append({ 'title': "end_working_time", 'date_start': end_working_time, 'date_end': end_working_time }) task_ids = [] if params['type'] == 'team': #Get all tasks on 'start_dt' for team task_ids = self.search(cr, uid, [ '&', ('date_start', '>=', datetime.strftime(start_working_time, timeDtFrmt)), ('date_start', '<=', datetime.strftime(end_working_time, timeDtFrmt)), '|', ('team_id', '=', params['calendar_id']), ('user_id', 'in', self.pool.get('openstc.team').read( cr, uid, params['calendar_id'], ['user_ids'])['user_ids']) ]) elif params['type'] == 'officer': #Get all tasks on 'start_dt' for officer task_ids = self.search(cr, uid, [ '&', ('date_start', '>=', datetime.strftime(start_working_time, timeDtFrmt)), ('date_start', '<=', datetime.strftime(end_working_time, timeDtFrmt)), '|', ('user_id', '=', params['calendar_id']), ('team_id', 'in', self.pool.get('res.users').read( cr, uid, params['calendar_id'], ['team_ids'])['team_ids']) ]) else: #Get all tasks on 'start_dt' for officer task_ids = self.search(cr, uid, [ '&', ('date_start', '>=', datetime.strftime(start_working_time, timeDtFrmt)), ('date_start', '<=', datetime.strftime(end_working_time, timeDtFrmt)), ('partner_id', '=', params['calendar_id']) ]) tasks = self.read(cr, uid, task_ids, ['name', 'date_start', 'date_end']) #Add tasks in list for task in tasks: events.append({ 'title': task['name'], 'date_start': datetime.strptime(task['date_start'], timeDtFrmt), 'date_end': datetime.strptime(task['date_end'], timeDtFrmt) }) #Sort task events.sort(key=operator.itemgetter('date_start')) params['events'] = events params['start_dt'] = start_dt #Return tasks return events
def assign_gajachhaya_yoga(self, debug_festivals=False): for d, daily_panchaanga in enumerate(self.daily_panchaangas): [y, m, dt] = [ daily_panchaanga.date.year, daily_panchaanga.date.month, daily_panchaanga.date.day ] # checking @ 6am local - can we do any better? local_time = tz(self.panchaanga.city.timezone).localize( datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # GAJACHHAYA YOGA if self.daily_panchaangas[ d].solar_sidereal_date_sunset.month == 6 and self.daily_panchaangas[ d].solar_sidereal_date_sunset.day == 1: moon_magha_jd_start = moon_magha_jd_start = t28_start = None moon_magha_jd_end = moon_magha_jd_end = t28_end = None moon_hasta_jd_start = moon_hasta_jd_start = t30_start = None moon_hasta_jd_end = moon_hasta_jd_end = t30_end = None anga_finder = zodiac.AngaSpanFinder.get_cached( ayanaamsha_id=self.computation_system.ayanaamsha_id, anga_type=zodiac.AngaType.SIDEREAL_MONTH) sun_hasta_jd_start, sun_hasta_jd_end = anga_finder.find( jd1=self.daily_panchaangas[d].jd_sunrise, jd2=self.daily_panchaangas[d].jd_sunrise + 30, target_anga_id=13).to_tuple() moon_magha_jd_start, moon_magha_jd_end = anga_finder.find( sun_hasta_jd_start - 2, sun_hasta_jd_end + 2, 10).to_tuple() if all([moon_magha_jd_start, moon_magha_jd_end]): anga_finder = zodiac.AngaSpanFinder.get_cached( ayanaamsha_id=self.computation_system.ayanaamsha_id, anga_type=zodiac.AngaType.TITHI) t28_start, t28_end = anga_finder.find( moon_magha_jd_start - 3, moon_magha_jd_end + 3, 28).to_tuple() anga_finder = zodiac.AngaSpanFinder.get_cached( ayanaamsha_id=self.computation_system.ayanaamsha_id, anga_type=zodiac.AngaType.NAKSHATRA) moon_hasta_jd_start, moon_hasta_jd_end = anga_finder.find( sun_hasta_jd_start - 1, sun_hasta_jd_end + 1, 13).to_tuple() if all([moon_hasta_jd_start, moon_hasta_jd_end]): anga_finder = zodiac.AngaSpanFinder.get_cached( ayanaamsha_id=self.computation_system.ayanaamsha_id, anga_type=zodiac.AngaType.TITHI) t30_start, t30_end = anga_finder.find( sun_hasta_jd_start - 1, sun_hasta_jd_end + 1, 30).to_tuple() gc_28 = gc_30 = False if all([sun_hasta_jd_start, moon_magha_jd_start, t28_start]): # We have a GC yoga gc_28_start = max(sun_hasta_jd_start, moon_magha_jd_start, t28_start) gc_28_end = min(sun_hasta_jd_end, moon_magha_jd_end, t28_end) if gc_28_start < gc_28_end: gc_28 = True if all([sun_hasta_jd_start, moon_hasta_jd_start, t30_start]): # We have a GC yoga gc_30_start = max(sun_hasta_jd_start, moon_hasta_jd_start, t30_start) gc_30_end = min(sun_hasta_jd_end, moon_hasta_jd_end, t30_end) if gc_30_start < gc_30_end: gc_30 = True if self.daily_panchaangas[ d].solar_sidereal_date_sunset.month == 6 and (gc_28 or gc_30): if gc_28: gc_28_d = 1 + floor(gc_28_start - self.panchaanga.jd_start) # sys.stderr.write('gajacchhaya %d\n' % gc_28_d) # gajacchaayaa_fest = FestivalInstance(name='gajacchAyA-yOgaH', interval=Interval(jd_start=gc_28_start, jd_end=gc_28_end), days=[self.daily_panchaangas[gc_28_d].date]) # self.panchaanga.festival_id_to_days[gajacchaayaa_fest.name] = gajacchaayaa_fest gc_28 = False if gc_30: # sys.stderr.write('30: (%f, %f)\n' % (gc_30_start, gc_30_end)) gc_30_d = 1 + floor(gc_30_start - self.panchaanga.jd_start) # gajacchaayaa_fest = FestivalInstance(name='gajacchAyA-yOgaH', interval=Interval(jd_start=gc_30_start, jd_end=gc_30_end), days=[self.daily_panchaangas[gc_30_d].date]) # self.panchaanga.festival_id_to_days[gajacchaayaa_fest.name] = gajacchaayaa_fest gc_30 = False
def as_qdatetime(datetime): "Create QDateTime set as specified by datetime." return QDateTime.fromSecsSinceEpoch( int(secs_since_epoch(datetime) - datetime.utcoffset() / timedelta(seconds=1)) )
output_collector = {} # year data that is not specified for each day samvatsara_id = (panchangam.year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = ( NAMES['SAMVATSARA_NAMES'][panchangam.script][samvatsara_id], NAMES['SAMVATSARA_NAMES'][panchangam.script][(samvatsara_id % 60) + 1]) yname = samvatsara_names[0] # Assign year name until Mesha Sankranti for d in range(1, temporal.MAX_SZ - 1): try: [y, m, dt, t] = swe.revjul(panchangam.jd_start_utc + d - 1) local_time = tz(panchangam.city.timezone).localize( datetime(y, m, dt, 6, 0, 0)) tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 jd = panchangam.jd_start_utc - tz_off / 24.0 + d - 1 sunrise = get_time_string(panchangam.jd_sunrise[d], jd) sunset = get_time_string(panchangam.jd_sunset[d], jd) moonrise = get_time_string(panchangam.jd_moonrise[d], jd) moonset = get_time_string(panchangam.jd_moonset[d], jd) rahu_start = get_time_string(panchangam.kaalas[d]['rahu'][0], jd) rahu_end = get_time_string(panchangam.kaalas[d]['rahu'][1], jd) yama_start = get_time_string(panchangam.kaalas[d]['yama'][0], jd) yama_end = get_time_string(panchangam.kaalas[d]['yama'][1], jd) gulika_start = get_time_string(panchangam.kaalas[d]['gulika'][0], jd) gulika_end = get_time_string(panchangam.kaalas[d]['gulika'][1], jd)