예제 #1
0
def get_evts(bot, timezone, type=None):
    result = []
    for evt in weekly_events:
        if type is not None and evt['type'] != type:
            continue
        evt_begin = evt['begin'].split(':')
        dt_evt_begin = DateUtil.get_dt_now(bot.tz_str).replace(
            hour=int(evt_begin[0]),
            minute=int(evt_begin[1]),
            second=0,
            microsecond=0
        )
        while dt_evt_begin.isoweekday() != int(evt['weekday']):
            dt_evt_begin += timedelta(days=1)
        dt_evt_begin = dt_evt_begin.replace(tzinfo=None)
        dt_evt_begin = timezone.localize(dt_evt_begin, is_dst=False)
        evt_end = evt['end'].split(':')
        dt_evt_end = DateUtil.get_dt_now(bot.tz_str).replace(
            hour=int(evt_end[0]),
            minute=int(evt_end[1]),
            second=0,
            microsecond=0
        )
        while dt_evt_end.isoweekday() != int(evt['weekday']):
            dt_evt_end += timedelta(days=1)
        dt_evt_end = dt_evt_end.replace(tzinfo=None)
        dt_evt_end = timezone.localize(dt_evt_end, is_dst=False)
        evt['dt_begin'] = dt_evt_begin
        evt['dt_end'] = dt_evt_end
        result.append(evt)
    result.sort(key=lambda x: x['dt_begin'])
    return result
예제 #2
0
    def format_request(self, date_to, date_from, time_zone, sale_statuses):
        print date_to.get(), date_from.get(), time_zone.get(
        ), sale_statuses.get()

        # Update all sales
        if sale_statuses.get() == "":
            status = ""
            print "yeap"

        fmt = "%Y-%m-%d %H:%M:%S"

        utc = pytz.utc
        utc.zone

        try:
            timezone = timezone(time_zone.get())
            print "timezone shii worked %s" % (timezone)
        except:
            print time_zone.get()
            print "time zone given is the wrong format"
            return False

        if date_from == "":
            date_from = date_to

        # Changes date and time entered to a datetime object
        dateToFormat = datetime.strptime(date_to, "%Y-%m-%d %H:%M:%S")
        dateFromFormat = datetime.strptime(date_from, "%Y-%m-%d %H:%M:%S")

        # Localize the datetime to the timezone specified
        dateToDateTime = timezone.localize(
            datetime(dateToFormat.year, dateToFormat.month, dateToFormat.day,
                     dateToFormat.hour, dateToFormat.minute,
                     dateToFormat.second))
        dateFromDateTime = timezone.localize(
            datetime(dateFromFormat.year, dateFromFormat.month,
                     dateFromFormat.day, dateFromFormat.hour,
                     dateFromFormat.minute, dateFromFormat.second))

        # Convert the datetime to UTC time
        self.dateToUTC = dateToDateTime.astimezone(utc)
        self.dateFromUTC = dateFromDateTime.astimezone(utc)

        # String format of the UTC time to help match with datetime format in API responses
        self.strdateToUTC = dateToUTC.strftime(fmt)
        self.strdateFromUTC = dateFromUTC.strftime(fmt)

        print strdateToUTC, strdateFromUTC

        saleResponse = register_sales(status)

        # Check how many pages the request has
        if sale_statuses.get() == "":
            check_pages(saleResponse)

        return False
예제 #3
0
def get_file_metadata(file_location):
    return {
        'creation_datetime':
        timezone.localize(
            datetime.fromtimestamp(os.path.getctime(file_location))),
        'modified_datetime':
        timezone.localize(
            datetime.fromtimestamp(os.path.getmtime(file_location))),
        'file_size_bytes':
        os.path.getsize(file_location),
    }
예제 #4
0
 def get_current_day(zone='UTC', add_hr=0):
     timezone = pytz.timezone(zone)
     dt = timezone.localize(datetime.now())
     format = "%Y-%m-%d 00:00:00"
     ret_day = datetime.strptime(dt.strftime(format),
                                 format) + timedelta(hours=int(add_hr))
     return ret_day
예제 #5
0
def fmt_timezone():
    """
    Return current time with format
    """
    timezone = get_timezone()
    loc_dt = timezone.localize(datetime.utcnow())
    return loc_dt.strftime('%b %d, %Y %H:%M:%S')
예제 #6
0
def check_incoming_transactions(user_id, n=0):
    user = User.query.filter_by(id=user_id).first()
    if user.is_authenticated:
        bundles = user.get_bundles(n)
        n = len(bundles)

        #Finds the amount of transactions in the database related
        #to the current user and compares it to the newly retrieved
        #bundle length. If equal, wait 120 seconds, try again. If
        #not equal, new transactions are added to db, then wait 120s.
        transaction_count = db.session.query(
            User.transactions).filter_by(id=user_id).count()
        print("Number of Transactions is: " + str(transaction_count))
        print("N is equal to: " + str(n))
        if n == transaction_count:
            print("NO NEW TRANSACTIONS")
            print(timezone.localize(datetime.now()) + timedelta(seconds=120))
            check_incoming_transactions.apply_async(
                (user_id, n),
                eta=timezone.localize(datetime.now()) + timedelta(seconds=120))
        else:
            print("NEW TRANSACTION INCOMING")
            new_messages = {}
            for message in bundles:
                tx = message[0]
                print(tx.address)
                #user_identifier = TryteString.decode(tx.signature_message_fragment)
                receiving_address = tx.address
                payment_amount = int(tx.value)
                timestamp = tx.timestamp

                incomingTransaction = Transaction(
                    transaction_id=str(uuid.uuid4()),
                    user_identifier=user.identifier,
                    payment_amount=payment_amount,
                    payment_address=receiving_address,
                    timestamp=timestamp)

                db.session.add(incomingTransaction)
                db.session.commit()
            check_incoming_transactions.apply_async(
                (user_id, n),
                eta=timezone.localize(datetime.now()) + timedelta(seconds=120))
    else:
        return False
예제 #7
0
 def test_1_supermoon(self):
     import pytz
     timezone = pytz.timezone("UTC")
     apogees, perigees = apsis(2049)
     dt = datetime.datetime(2049, 8, 13, 9, 20)
     dt_aware = timezone.localize(dt)
     result = apsisconincidence(apogees, perigees, dt_aware)
     self.assertFalse(result['within 24 hours']['apogee'])
     self.assertTrue(result['within 24 hours']['perigee'])
예제 #8
0
def _make_aware(value, timezone):
    """
    Makes a naive datetime.datetime in a given time zone aware.
    """
    if hasattr(timezone, 'localize'):
        # available for pytz time zones
        return timezone.localize(value, is_dst=None)
    else:
        # may be wrong around DST changes
        return value.replace(tzinfo=timezone)
예제 #9
0
def _make_aware(value, timezone):
    """
    Makes a naive datetime.datetime in a given time zone aware.
    """
    if hasattr(timezone, 'localize'):
        # available for pytz time zones
        return timezone.localize(value, is_dst=None)
    else:
        # may be wrong around DST changes
        return value.replace(tzinfo=timezone)
예제 #10
0
def update_balance(user_id):
    user = User.query.filter_by(id=user_id).first()
    if user.is_authenticated:
        user.balance = user.get_balance()
        print("Users balance is " + str(user.balance))
        db.session.commit()
        update_balance.apply_async(
            (user_id, ),
            eta=timezone.localize(datetime.now()) + timedelta(seconds=120))
    else:
        return False
예제 #11
0
def execute_agreement(user_id, client_id):

    payment_agreement = PaymentAgreement.query.filter_by(
        user_id=user_id, client_id=client_id).first()

    transaction = payment_agreement.send_payment()

    if type(transaction) is Transaction:
        return execute_agreement.apply_async(
            (user_id, client_id),
            eta=timezone.localize(datetime.now()) +
            timedelta(seconds=payment_agreement.payment_time))
    else:
        print("Transaction was not successful.")
        payment_agreement.is_active = 0
        db.session.commit()
        return False
예제 #12
0
    def fromHex(self, hex, timezone=utc):
        if len(hex) == 128:
            self.date            = datetime.datetime(2000+int(hex[0:2], 16), int(hex[2:4], 16), int(hex[4:6], 16), int(hex[6:8], 16), int(hex[8:10], 16), int(hex[10:12], 16))
            self.trackpointCount = int(Utilities.swap(hex[12:16]), 16)
            self.duration        = datetime.timedelta(seconds=int(Utilities.swap(hex[16:24]), 16)/10)
            self.distance        = int(Utilities.swap(hex[24:32]), 16)
            self.lapCount        = int(Utilities.swap(hex[32:36]), 16)
            self.pointer         = hex[36:40]
            self.calories        = int(Utilities.swap(hex[48:52]), 16)
            self.topspeed        = int(Utilities.swap(hex[56:64]), 16)/100
            self.climb           = int(Utilities.swap(hex[68:72]), 16)

            # localize date and then convert to UTC
            self.date = timezone.localize(self.date).astimezone(utc)
            return self
        else:
            raise GB500ParseException(self.__class__.__name__, len(hex), 128)
예제 #13
0
    def fromHex(self, idx, hex, timezone=utc, units=""): 
        self.index           = idx
        self.date            = datetime.datetime(2000+int(hex[0:2], 16), int(hex[2:4], 16), int(hex[4:6], 16), int(hex[6:8], 16), int(hex[8:10], 16), int(hex[10:12], 16))
        self.trackpointCount = int(Utilities.swap(hex[12:16]), 16)
        self.duration        = datetime.timedelta(seconds=int(Utilities.swap(hex[16:24]), 16)/10)
        self.distance        = float(int(Utilities.swap(hex[24:32]), 16))
        self.lapCount        = int(hex[32:36], 16)
        self.pointer         = hex[36:40]

        # localize date
        self.date = timezone.localize(self.date)
        # todo support for imperial units
        if units == "imperial":
            self.distance = round(self.distance * 0.000621371, 1)
        else:
            self.distance = round(self.distance * 0.001, 1)
        return self
예제 #14
0
def timezone_example():
    from datetime import datetime
    import pytz
    d = datetime.now()
    timezone = pytz.timezone("Australia/Sydney")
    date_timezone_aware = timezone.localize(d)
    print(
        f"The Time is {date_timezone_aware} where the TZ is {date_timezone_aware.tzinfo}"
    )

    #pytz
    # https://www.journaldev.com/23370/python-pytz Thanks !
    # interesting info on the country / city combos : https://www.iso.org/iso-3166-country-codes.html
    print('all_timezones =', pytz.all_timezones, '\n')

    print('country_names =')
    for key, val in pytz.country_names.items():
        print(key, '=', val, end=',')
    print('\n')
    print('IN full name =', pytz.country_names['IN'])
예제 #15
0
def schedule_to_service_calendar(sched, agency_id):
    timezone = timezone_from_agency(sched, agency_id)

    day_start, day_end = day_bounds_from_sched(sched)

    startdate, enddate = [ datetime.datetime( *parse_date(x) ) for x in sched.GetDateRange() ]

    cal = ServiceCalendar()

    for currdate in iter_dates(startdate, enddate):
        local_dt = timezone.localize(currdate)

        service_ids = [x.encode("ascii") for x in get_service_ids( sched, currdate )]

        this_day_begins = timezone.normalize( local_dt + timedelta(seconds=day_start) )
        this_day_ends = timezone.normalize( local_dt + timedelta(seconds=day_end)  )

        cal.add_period( TimeHelpers.datetime_to_unix(this_day_begins), TimeHelpers.datetime_to_unix(this_day_ends), service_ids )

    return cal
예제 #16
0
def convertDateToGoogleStr(timezone, d):
    dateStr = timezone.normalize(timezone.localize(d)).astimezone(tz.tzutc()).isoformat('T')
    return dateStr
예제 #17
0
# Set times
start_year = 2019
start_month = month
start_day = 1

end_year = 2019
end_month = month
#end_day = monthrange(end_year, end_month)[1]
end_day = 1

# set start and end date
start = datetime.datetime(start_year, start_month, start_day, hour=0)
end = datetime.datetime(end_year, end_month, end_day, hour=23)
timezone = pytz.timezone("utc")
start = timezone.localize(start)
end = timezone.localize(end)

# Load data
# Data from "urbanova_mapping_1.33km.py"
name = base_dir + '1p33_' + start.strftime("%Y%m%d") + '_' + end.strftime(
    "%Y%m%d")  #+'_PST'


def load_obj(name):
    with open(name + '.pkl', 'rb') as f:
        return pickle.load(f)


airpact = load_obj(name)
예제 #18
0
 def getcurr_datetime(zone='UTC', add_hr=0):
     timezone = pytz.timezone(zone)
     dt = timezone.localize(datetime.now())
     format = "%Y-%m-%d %H:%M:%S"
     return datetime.strptime(dt.strftime(format),
                              format) + timedelta(hours=int(add_hr))
예제 #19
0
    def test_normal_datetime_timezone(self, value, timezone, expected):
        result = typepy.DateTime(value,
                                 strict_level=StrictLevel.MIN,
                                 timezone=timezone).convert()

        assert result == timezone.localize(expected)
예제 #20
0
 def getcurr_datetime_String(zone='UTC', format="%Y-%m-%dT%H:%M:%SZ"):
     timezone = pytz.timezone(zone)
     dt = timezone.localize(datetime.now())
     return dt.strftime(format)
예제 #21
0
def pre_process_dataset(cells_df, same_position_base_stations, dataset_basepath, label, \
                        time_period_in_minutes, output_basepath, ranges, aggregation_type, put_zeroes):
    traffic_volume_output_filepath = output_basepath + "/traffic_load.dat"
    print "> Writing file %s" % traffic_volume_output_filepath
    if not os.path.exists(output_basepath):
        os.makedirs(output_basepath)

    files_list = os.listdir(dataset_basepath)
    files_list.sort()

    unique_base_stations = [
        cell_id for cell_id in cells_df.index
        if not cell_id in same_position_base_stations
    ]
    all_cells = [
        cell_id
        for same_position_cells in same_position_base_stations.values()
        for cell_id in same_position_cells
    ] + unique_base_stations
    '''parser = lambda x: timezone('UTC')\
        .localize(datetime.datetime.utcfromtimestamp(int(x)))\
        .astimezone(timezone('CET')).strftime("%Y-%m-%d %H:%M:%S")'''
    first = True
    for filename in files_list:
        if not filename.startswith("TCPSessCourtParisLyon_"):
            continue

        date_format = filename.split(
            "_")  #format is TCPSessCourtParisLyon_300_2016_09_nidt
        traffic_volume_filepath = dataset_basepath + '/' + filename
        names = ['datetime', 'cell_id', 'category', 'uplink', 'downlink']
        traffic_df = pd.read_csv(
            traffic_volume_filepath, sep=';', header=None,
            names=names)  #, parse_dates=[0], date_parser=parser)
        #print "Number of lines in %s: %d" %(filename, len(traffic_df))
        #traffic_df = traffic_df[traffic_df.category.isin(traffic_kind)] #filtering by category
        #print "Number of lines in %s after filtering to categories %s: %d" %(filename, str(traffic_kind), len(traffic_df))
        # filter to relevant cells
        traffic_df = traffic_df[traffic_df['cell_id'].isin(all_cells)]
        print "Number of lines in %s after filtering to selected cells: %d" % (
            filename, len(traffic_df))
        traffic_df["datetime"] = pd.to_datetime(
            traffic_df.datetime,
            unit='s').apply(lambda x: x.tz_localize('UTC'))
        traffic_df = traffic_df.groupby(['datetime', 'cell_id',
                                         'category']).sum()
        traffic_df = traffic_df.reset_index()
        #bad date --->>>>>traffic_df["datetime"] = pd.to_datetime(traffic_df["datetime"])
        time_period_in_minutes = str(time_period_in_minutes)

        print "Considering sum of uplink and downlink for selected service categories..."
        if aggregation_type == 'uplink':
            traffic_df['traffic_load'] = traffic_df['uplink']
        elif aggregation_type == 'downlink':
            traffic_df['traffic_load'] = traffic_df['downlink']
        else:
            traffic_df[
                'traffic_load'] = traffic_df['uplink'] + traffic_df['downlink']
        #traffic_df = traffic_df[(traffic_df.datetime >= ranges[0] + " 00:00:00") & (traffic_df.datetime <= ranges[1] + " 23:59:59")]
        if put_zeroes:
            traffic_df = traffic_df[[
                'datetime', 'cell_id', 'category', 'traffic_load'
            ]]
            traffic_df = traffic_df.set_index("datetime").groupby(
                ["cell_id",
                 "category"]).resample(time_period_in_minutes + 'Min').sum()
            traffic_df = traffic_df.reset_index()
            # get communication data (sms+call french and non-french)
            year = int(date_format[2])
            month = int(date_format[3])
            day = int(date_format[4])
            next_year = int(date_format[5])
            next_month = int(date_format[6])
            next_day = int(date_format[7])
            timezone = pytz.timezone("Europe/Paris")
            date_from = datetime.datetime(year, month, day, 0, 0, 0)
            date_from = timezone.localize(date_from)
            date_to = datetime.datetime(next_year, next_month, next_day, 0, 0,
                                        0)
            date_to = timezone.localize(date_to)
            timezone = pytz.timezone("UTC")
            date_from = date_from.astimezone(timezone)
            date_to = date_to.astimezone(timezone)
            num_days = (date_to - date_from).days + 1
            num_periods = num_days * round(
                24.0 * 60.0 / int(time_period_in_minutes))
            print "Checking daylight saving change"
            day_light_savings_change_positive = (next_month == 10
                                                 and next_day == 31
                                                 and month == 10 and day == 1)
            day_light_savings_change_negative = (next_month == 3
                                                 and next_day == 31
                                                 and month == 3 and day == 1)
            if day_light_savings_change_positive:
                old_num_periods = num_periods
                num_periods += 1 * 60.0 / int(time_period_in_minutes)
                print "Positive daylight saving change detected. Adding %d slots to num_periods: %d" % (
                    old_num_periods - num_periods, num_periods)
            elif day_light_savings_change_negative:
                old_num_periods = num_periods
                num_periods -= 1 * 60.0 / int(time_period_in_minutes)
                print "Negative daylight saving change detected. Removing %d slots to num_periods: %d" % (
                    old_num_periods - num_periods, num_periods)
            else:
                print "No daylight saving change detected"
            hour_range = pd.date_range(date_from,
                                       periods=num_periods,
                                       freq=str(time_period_in_minutes) +
                                       'Min',
                                       tz="UTC")
            print "There are %d categories in the dataset..." % (
                len(CATEGORIES))
            print str(CATEGORIES)
            index = [[d, cell, c] for cell in all_cells for d in hour_range
                     for c in CATEGORIES]
            # this df will be just an index
            temp_df = pd.DataFrame(index)
            temp_df.columns = ['datetime', 'cell_id', 'category']
            temp_df = temp_df.set_index(['datetime', 'cell_id', 'category'])
            traffic_df = traffic_df.set_index(
                ["datetime", "cell_id", 'category'])
            traffic_df = traffic_df.reindex_axis(temp_df.index).fillna(0)
            traffic_df = traffic_df.reset_index()
        else:
            traffic_df = traffic_df.set_index("datetime").groupby(
                ["cell_id",
                 'category']).resample(time_period_in_minutes + 'Min',
                                       how='sum',
                                       base=0)
            traffic_df = traffic_df.reset_index()
            traffic_df = traffic_df[[
                'datetime', 'cell_id', 'category', 'traffic_load'
            ]]
            traffic_df = traffic_df[np.isfinite(traffic_df['traffic_load'])]

        for new_id in same_position_base_stations:
            subset_df = traffic_df[traffic_df["cell_id"].isin(
                same_position_base_stations[new_id])]
            subset_df = subset_df.groupby(["datetime", 'category']).sum()
            subset_df = subset_df.reset_index()
            traffic_df = traffic_df[~traffic_df["cell_id"].
                                    isin(same_position_base_stations[new_id])]
            subset_df["cell_id"] = new_id
            traffic_df = traffic_df.append(subset_df, ignore_index=True)

        traffic_df["datetime"] = traffic_df["datetime"].apply(
            lambda x: x.tz_convert('CET'))
        traffic_df['#name_of_the_day'] = traffic_df['datetime'].apply(
            lambda x: x.strftime('%A'))
        traffic_df['date'] = traffic_df['datetime'].apply(
            lambda x: x.strftime('%Y-%m-%d'))
        traffic_df['time'] = traffic_df['datetime'].apply(
            lambda x: x.strftime('%H:%M:%S'))
        traffic_df['aggregation'] = label

        traffic_df = pd.merge(traffic_df,
                              cells_df,
                              left_on='cell_id',
                              right_index=True)

        traffic_df = traffic_df.rename(columns={'X': 'lon', 'Y': 'lat'})
        traffic_df = traffic_df[[
            "#name_of_the_day", "date", "time", "cell_id", "lon", "lat",
            "aggregation", 'category', "traffic_load"
        ]]
        traffic_df = traffic_df.sort_values(by=["date", "time"])
        #print traffic_df.head()
        grouped_traffic_df = traffic_df.groupby([
            "#name_of_the_day", "date", "time", "cell_id", "lon", "lat",
            "aggregation", 'category'
        ])
        #size = grouped_traffic_df.size()
        #print "Should be not empty only with positive daylight traffic change..."
        #print size[size > 1].head()
        #print size[size > 1].tail()
        traffic_df = grouped_traffic_df.sum()
        traffic_df = traffic_df.reset_index()
        traffic_df = traffic_df[[
            "#name_of_the_day", "date", "time", "cell_id", "lon", "lat",
            "aggregation", 'category', "traffic_load"
        ]]
        traffic_df = traffic_df.sort_values(by=['date', 'time', 'cell_id'])
        # final_df[['traffic_load']] = final_df[['traffic_load']].astype(int)

        if first:
            first = False
            traffic_df.to_csv(traffic_volume_output_filepath,
                              sep=" ",
                              index=False)
        else:
            traffic_df.to_csv(traffic_volume_output_filepath,
                              sep=" ",
                              mode="a",
                              header=False,
                              index=False)
예제 #22
0
 def get_TodayStr(zone='UTC'):
     timezone = pytz.timezone(zone)
     dt = timezone.localize(datetime.now())
     format = "%Y-%m-%d %H:%M:%S"
     return datetime.strptime(dt.strftime(format), format)
     return tody.strftime('%Y-%m-%d 00:00')
예제 #23
0
def set_date():
    date = datetime.now()
    timezone = pytz.timezone("Asia/Kolkata")
    d_aware = timezone.localize(date)
    date_format = "%d-%b-%Y %H:%M:%S"
    return date, date_format
예제 #24
0
    async def reminder(self, ctx, *args):
        '''Set a reminder! (format: oki.reminder <w>d <x>h <y>m <z>s <message>)'''

        member = ctx.author
        day = 0
        hour = 0
        mins = 0
        sec = 0
        msg = "default"
        count = 0
        timezone = pytz.timezone("America/Los_Angeles")
        present_time = datetime.now()
        pp_time = timezone.localize(present_time)
        p_time = pp_time.strftime("%b %d, %I:%M:%S %Z")
        print("present time at LV is " + p_time)
        # oki.reminder 1d 3h 3m 2s WOOT
        dCount = 0
        hCount = 0
        mCount = 0
        sCount = 0
        while args[count][0].isnumeric() and args[count][-1].isalpha(
        ) and count < 4:
            if args[count][-1] == 'd':
                dCount += 1
                if dCount < 2:
                    day = int(args[count][:-1])
                else:
                    break

            elif args[count][-1] == 'h':
                hCount += 1
                if hCount < 2:
                    hour = int(arg[count][:-1])
                else:
                    break

            elif args[count][-1] == 'm':
                mCount += 1
                if mCount < 2:
                    mins = int(args[count][:-1])
                else:
                    break

            elif args[count][-1] == 's':
                sCount += 1
                if sCount < 2:
                    sec = int(args[count][:-1])
                else:
                    break

            print(args[count][-1])
            print(args[count][:-1])
            print(count)
            count += 1

        msg = ' '.join(args[count:])

        await ctx.send("days: " + str(day) + ", hours: " + str(hour) +
                       ", minutes: " + str(mins) + ", seconds: " + str(sec))
        update_time = datetime.now() + timedelta(
            days=day, hours=hour, minutes=mins, seconds=sec)
        u_time = update_time.strftime("%b %d, %I:%M:%S")
        print("updated time at LV is " + u_time)
        while u_time >= p_time:
            present_time = datetime.now()
            pp_time = timezone.localize(present_time)
            p_time = pp_time.strftime("%b %d, %I:%M:%S")
            # print("this is current present time: " +
            # p_time + ", reminder: " + u_time)

            await asyncio.sleep(1)
        await member.send(msg)
예제 #25
0
try:
    start_date = date(*map(int, sys.argv[2].split('-')))
except:
    print 'Scanning service calendar to find the month with maximum service.'
    print 'NOTE that this is not necessarily accurate and you can end up with sparse service in the chosen period.'
    start_date = db.find_max_service()
print 'calendar start date is %s' % start_date

timezones = db.agency_timezones()
if len(db.agency_timezones()) > 1:
    print 'Currently we only support one timezone being active, selected: ' + timezones[
        0]
print 'using timezone ' + timezones[0]

timezone = timezone(timezones[0])
start_time = timezone.localize(
    datetime.datetime.combine(start_date, datetime.time.min))
#Check whether DST is active on the serviceday, that means AFTER 3am, hence the +1 day.
dst_active = start_time.timetuple().tm_isdst
if dst_active == 1:
    print 'DST active on start_time, adding one hour to start_time'
calendar_start_time = time.mktime(
    (start_time + timedelta(hours=dst_active)).timetuple())
print 'epoch time at which calendar starts: %d' % calendar_start_time

sids = db.service_ids()
print '%d distinct service IDs' % len(sids)

bitmask_for_sid = {}
dst_mask = 0
for sid in sids:
    bitmask_for_sid[sid] = 0
예제 #26
0
def convert_time_to_balanced_time(time=None, zipcode=10010, pretty_print=False):
    #zipcodes to lat/long to astral's location
    search = SearchEngine(simple_zipcode=True) # set simple_zipcode=False to use rich info database
    zipcode_obj = search.by_zipcode(zipcode)
    #the below won't work outside the US, need to reconcile uszipcode's timezone with atral's timezone
    location = astral.Location(('name', 'region', zipcode_obj.lat, zipcode_obj.lng, "US/"+zipcode_obj.timezone, 0))
    if time is None:
        now = datetime.now()
    else:
        now = time
        
    timezone = pytz.timezone(location.timezone)
    time = timezone.localize(now)
    #print(time)
    
    beginning_of_today = datetime(time.year, time.month, time.day)
    sun = location.sun(date=beginning_of_today, local=True)
    #print(sun)
    #print()
    
    beginning_of_yesterday = datetime(time.year, time.month, time.day) - timedelta(days=1)
    sun_yesterday = location.sun(date=beginning_of_yesterday, local=True)
    
    beginning_of_tomorrow = datetime(time.year, time.month, time.day) + timedelta(days=1)
    sun_tomorrow = location.sun(date=beginning_of_tomorrow, local=True)

    six_am = datetime(time.year, time.month, time.day, 6)
    six_pm = datetime(time.year, time.month, time.day, 18)

    todays_seconds = sun['sunset'] - sun['sunrise']
    #print("todays seconds: "+str(todays_seconds.total_seconds())+" or "+str(todays_seconds)+" hours.")
    
    last_nights_seconds = sun['sunrise'] - sun_yesterday['sunset']
    #print("last night's seconds: "+str(last_nights_seconds.total_seconds())+" or "+str(last_nights_seconds)+" hours.")
    
    tonights_seconds = sun_tomorrow['sunrise'] - sun['sunset']
    #print("tonight's seconds: "+str(tonights_seconds.total_seconds())+" or "+str(tonights_seconds)+" hours.")
    
    seconds_from_time_to_next_sunrise = sun['sunrise'] - time #use sun, not sun_tomorrow, because pre-dawn is same day
    #print("seconds_from_time_to_sunrise"+str(seconds_from_time_to_next_sunrise.total_seconds()))
    seconds_from_sunrise_to_time = time - sun['sunrise'] #same-day
    #print("seconds_from_sunrise_to_time"+str(seconds_from_sunrise_to_time.total_seconds()))
    seconds_from_sunset_until_time = time - sun['sunset']  #same-day, at night after sunset
    #print("seconds_from_sunset_to_time"+str(seconds_from_sunset_until_time.total_seconds()))
    
    balanced_seconds = timedelta(seconds=12*60*60)
    
    multiplier_how_much_shorter_today_is = balanced_seconds / todays_seconds
    #print("today's shortness multiplier, each second moves at x"+str(multiplier_how_much_shorter_today_is))
    
    multiplier_how_much_longer_tonight_is = (balanced_seconds / tonights_seconds)
    #print("tonight's multiplier: , each second moves at x"+str(multiplier_how_much_longer_tonight_is))
    
    multiplier_how_much_longer_last_night_was = (balanced_seconds / last_nights_seconds)
    #print("last night's multiplier: , each second moves at x"+str(multiplier_how_much_longer_last_night_was))

    if time >= sun['sunrise'] and time <= sun['sunset']:
        seconds_to_add_to_six_am = seconds_from_sunrise_to_time.total_seconds()*multiplier_how_much_shorter_today_is
        #print("seconds to add to today's 6 AM: "+str(seconds_to_add_to_six_am)+", or "+str(seconds_to_add_to_six_am/60/60)+" hours.")
        modified_time = six_am + timedelta(seconds=(seconds_to_add_to_six_am))

    elif time < sun['sunrise']: 
        seconds_to_subtract_from_this_six_am = seconds_from_time_to_next_sunrise.total_seconds()*(multiplier_how_much_longer_last_night_was)
        #print("seconds to subtract from this 6 am: "+str(seconds_to_subtract_from_this_six_am)+", or "+str(seconds_to_subtract_from_this_six_am/60/60)+" hours.")
        modified_time = six_am - timedelta(seconds=(seconds_to_subtract_from_this_six_am))
        

    elif time > sun['sunset']:        
        seconds_to_add_to_tonights_six_pm = seconds_from_sunset_until_time.total_seconds()*multiplier_how_much_longer_tonight_is
        #print("seconds to add to tonight's 6 PM: "+str(seconds_to_add_to_tonights_six_pm)+", or "+str(seconds_to_add_to_tonights_six_pm/60/60)+" hours.")
        modified_time = six_pm + timedelta(seconds=(seconds_to_add_to_tonights_six_pm))
    if pretty_print == False:
        return modified_time 
    else:
        return modified_time.strftime("%I:%M:%S %p")
예제 #27
0
파일: timetable.py 프로젝트: Medusis/rrrr
# second command line parameter: start date for 32-day calendar
try :
    start_date = date( *map(int, sys.argv[2].split('-')) )
except :
    print 'Scanning service calendar to find the month with maximum service.'
    print 'NOTE that this is not necessarily accurate and you can end up with sparse service in the chosen period.'
    start_date = db.find_max_service()
print 'calendar start date is %s' % start_date

timezones = db.agency_timezones()
if len(db.agency_timezones()) > 1:
    print 'Currently we only support one timezone being active, selected: '+timezones[0]
print 'using timezone '+timezones[0]

timezone = timezone(timezones[0])
start_time = timezone.localize(datetime.datetime.combine(start_date, datetime.time.min))
#Check whether DST is active on the serviceday, that means AFTER 3am, hence the +1 day.
dst_active = start_time.timetuple().tm_isdst
if dst_active == 1:
    print 'DST active on start_time, adding one hour to start_time'
calendar_start_time = time.mktime((start_time+timedelta(hours=dst_active)).timetuple())
print 'epoch time at which calendar starts: %d' % calendar_start_time

sids = db.service_ids()
print '%d distinct service IDs' % len(sids)
                    
bitmask_for_sid = {}
dst_mask = 0
for sid in sids :
    bitmask_for_sid[sid] = 0
for day_offset in range(32) :
예제 #28
0
 def to_utc(self, timezone, naive):
     return timezone.normalize(timezone.localize(naive)).astimezone(pytz.utc)