Как округлить столбец даты и времени до ближайшего квартала

Начать уведомление как:

private void startNotification(){
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager notificationManager = 
            (NotificationManager) getSystemService(ns);

    Notification notification = new Notification(R.drawable.ic_launcher, null, 
            System.currentTimeMillis());

    RemoteViews notificationView = new RemoteViews(getPackageName(),
            R.layout.mynotification);

    //the intent that is started when the notification is clicked (works)
    Intent notificationIntent = new Intent(this, FlashLight.class);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, 
            notificationIntent, 0);

    notification.contentView = notificationView;
    notification.contentIntent = pendingNotificationIntent;
    notification.flags |= Notification.FLAG_NO_CLEAR;

    //this is the intent that is supposed to be called when the 
    //button is clicked
    Intent switchIntent = new Intent(this, switchButtonListener.class);
    PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, 
            switchIntent, 0);

    notificationView.setOnClickPendingIntent(R.id.closeOnFlash, 
            pendingSwitchIntent);

    notificationManager.notify(1, notification);
}


public static class switchButtonListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("Here", "I am here");
        FlashOnOff flashLight;
        flashLight = new FlashOnOff();
        flashLight.flashLightOff();
        flashLight.releaseCamera();         
    }
}

xml used:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="horizontal"
android:weightSum="100" >

<ImageView
    android:id="@+id/notifiation_image"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="30"
    android:contentDescription="@string/appImage"
    android:src="@drawable/ic_launcher" />

<TextView
    android:id="@+id/appName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="50"
    android:gravity="center"
    android:text="@string/flashLightOn"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
    android:id="@+id/closeOnFlash"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="20"
    android:text="@string/close" />

В манифесте под тегом приложения:

<receiver android:name="FlashLight$switchButtonListener" />
29
задан Community 23 May 2017 в 10:30
поделиться

3 ответа

Предполагая, что ваша серия состоит из datetime объектов, вам необходимо использовать Series.apply. Пример -

import datetime
df['<column>'] = df['<column>'].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour,15*(dt.minute // 15)))

Приведенный выше пример всегда округляет до предыдущего квартала (поведение аналогично функции пола).

РЕДАКТИРОВАТЬ

Округлить до правильного четверть часа (например, если его 7 минут 30 секунд после предыдущего квартала показать следующий квартал). Мы можем использовать приведенный ниже пример -

import datetime
df['<column>'] = df['<column>'].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour,15*round((float(dt.minute) + float(dt.second)/60) / 15)))

Приведенное выше будет учитывать только самые последние секунды, если вы хотите учесть миллисекунду / микросекунду, вы можете добавить это к вышеприведенному уравнению как - (float(dt.minute) + float(dt.second)/60 + float(dt.microsecond)/60000000)

32
ответ дан Anand S Kumar 23 May 2017 в 10:30
поделиться

Это выглядит немного лучше

column.dt. позволяет функции datetime для столбцов datetime, как column.str. делает для строковых столбцов

datetime-like properties Справочник по API

import pandas as pd

# test df
df = pd.DataFrame([{'old_column':pd.Timestamp('2015-07-18 13:53:33.280')}])

df['new_column'] = df['old_column'].dt.round('15min')

df
11
ответ дан Laurens Koppenol 23 May 2017 в 10:30
поделиться

Ответ Ананда С. Кумара не округляется до ближайшей четверти часа, он обрезает минуты до ближайших 15 минут под ним.

На самом деле, в вашем примере 2015-07-18 13:53:33.280 следует округлить до 2015-07-18 14:00:00.000, поскольку 53:33.280 ближе к 60 минутам, чем к 45 минутам.

Я нашел более надежный ответ для округления в в этом посте .

Для вашей ситуации это должно работать:

import datetime

def round_time(time, round_to):
    """roundTo is the number of minutes to round to"""
    rounded = time + datetime.timedelta(minutes=round_to/2.)
    rounded -= datetime.timedelta(minutes=rounded.minute % round_to,
                                  seconds=rounded.second,
                                  microseconds=rounded.microsecond)
    return rounded

dt['dtcolumn'] = df['dtcolumn'].apply(lambda x: round_time(x))
6
ответ дан Community 23 May 2017 в 10:30
поделиться
Другие вопросы по тегам:

Похожие вопросы: