将日期时间的str列表转换为日期时间

时间:2017-12-12 06:45:50

标签: python pandas datetime

我正在关联两个数据帧以检查访问是否发生。

List<ContactPOJO> list_contact;
List<ContactPOJO> list_selected_contact = new ArrayList();
for (ContactPOJO pojo : list_contact){
    pojo.setIs_selected(true);
    list_selected_contact.add(pojo);
}

以上栏目的输出是:

def visiter(d,visits):
    visit = visits[d.start_date:d.end_date]
    out = visit[(visit['user_id'] == d.user_id)&(visit['merchant_id']==d.merchant_id)].head(1) #only take the first visit
    return (out.index.date.astype('str'))

data['visited_at']= data.apply(lambda x: str(visiter(x,visits)),axis =1 )

使用0 [] 1 [] 2 ['2017-04-24'] 3 [] 4 [] Name: visited_at, dtype: object 转换列,生成整个列pd.to_datetime(data.visited_at, errors = 'coerce')

我是否可以使用正确的格式更改日期时间,如下所示:NAT

EDIT1: 数据框如下所示:

2017-05-01 00:00:00

2 个答案:

答案 0 :(得分:1)

您需要strip删除[]

pd.to_datetime(data['visited_at'].str.strip('[]'), errors = 'coerce')
data['visited_at'] = pd.to_datetime(data['visited_at'].str.strip('[]'), errors = 'coerce')
print (data)

                        Index    id     user_id merchant_id  \
0 68989  68990  13277      38   437  2016-04-11    00:00:00   
1 403557 403558 195246    179  2218  2017-06-09    00:00:00   
2 333381 333382 127359    514  1820  2017-04-24    00:00:00   
3 511815 511816 151653    259  1136  2017-08-05    00:00:00   
4 167172 167173 51546      32   363  2016-08-05    00:00:00   

                       marketing_email_id start_date  end_date  email_status  \
0 68989  68990  13277          2016-04-16   00:00:00         1           NaN   
1 403557 403558 195246         2017-06-12   00:00:00         0           1.0   
2 333381 333382 127359         2017-05-01   00:00:00         0           1.0   
3 511815 511816 151653         2017-08-08   00:00:00         0           1.0   
4 167172 167173 51546          2016-08-15   00:00:00         1           NaN   

                        sms_status created_at visited_at  
0 68989  68990  13277   2016-04-11   11:05:31        NaT  
1 403557 403558 195246  2017-06-09   06:01:04        NaT  
2 333381 333382 127359  2017-04-24   10:00:33 2017-04-24  
3 511815 511816 151653  2017-08-05   11:31:19        NaT  
4 167172 167173 51546   2016-08-05   12:00:43        NaT  

另一个解决方案是检查是否为空df,并选择[0] if-else的第一个值:

def visiter(d,visits):
    visit = visits[d.start_date:d.end_date]
    out=visit[(visit['user_id'] == d.user_id)&(visit['merchant_id']==d.merchant_id)].head(1)
    out = np.nan if out.empty else out.index.date[0]
    return (out)

答案 1 :(得分:0)

add_action('woocommerce_cart_contents', 'mm_woocommerce_cart_contents'); /** * Cart Additional Products List Fragment */ function mm_woocommerce_cart_contents(){ // @Note: Modify WP_Query arguments below to get the products you are looking for $args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'post__not_in' => wp_list_pluck(WC()->cart->get_cart(), 'product_id'), ); // Set the query $products = new WP_Query( $args ); //Starting output buffering ob_start(); // Standard loop if ( $products->have_posts() ) : while ( $products->have_posts() ) : $products->the_post(); $_product = wc_get_product( $post ); // Making sure that In Stock or Backorder Allowed products are not // shown so there are no out-of-stock errors when updating cart if (! ( $_product->is_in_stock() || $_product->backorders_allowed() ) ) { continue; } ?> <!-- @Note: Modify HTML structure below this line in case you are using modified cart.php in your theme --> <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $_product ) ); ?>"> <td class="product-name"> <?php if ( ! $_product->is_visible() ) echo apply_filters( 'woocommerce_cart_item_name', $_product->get_title() ) . '&nbsp;'; else echo apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s </a>', $_product->get_permalink(), $_product->get_title() ) ); ?> </td> <td class="product-quantity"> <?php if( $_product->is_sold_individually() ) { $max_value = 1; } else { $max_value = $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(); } $product_quantity = woocommerce_quantity_input( array( 'input_name' => "mm_additional_products[{$_product->id}]", 'input_value' => '0', 'max_value' => $max_value, 'min_value' => '0' ), $_product ); ?> </td> <td class="product-price"> <?php echo WC()->cart->get_product_price( $_product ); ?> </td> <td class="product-subtotal"> <?php echo '--'; ?> </td> <td class="product-remove"> <?php echo '--'; ?> </td> </tr> <?php endwhile; wp_reset_postdata(); endif; // Echoing HTML from the loop above. echo ob_get_clean(); } 中的值是否实际列出(/* * Multi Add to Cart Functions * * Modified version of * https://dsgnwrks.pro/snippets/woocommerce-allow-adding-multiple-products-to-the-cart-via-the-add-to-cart-query-string/ */ function mm_add_to_cart_additional_products( $url = false ) { // Make sure WC is installed, and mm_additional_products query arg exists. if ( ! class_exists( 'WC_Form_Handler' ) || empty( $_REQUEST['mm_additional_products'] ) ) { return; } // Remove WooCommerce's hook, as it's useless (doesn't handle multiple products). remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 ); // Handle products with zero quantity from the array and assign $product_ids = array_map( 'intval', $_REQUEST['mm_additional_products'] ); $product_ids = array_filter( $product_ids, function( $v ){ return $v > 0; }); $count = count( $product_ids ); $number = 0; foreach ( $product_ids as $product_id => $quantity ) { //$id_and_quantity $_REQUEST['quantity'] = $quantity; if ( ++$number === $count ) { // Ok, final item, let's send it back to woocommerce's add_to_cart_action method for handling. $_REQUEST['add-to-cart'] = $product_id; return WC_Form_Handler::add_to_cart_action( $url ); } $product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $product_id ) ); $was_added_to_cart = false; $adding_to_cart = wc_get_product( $product_id ); // If a there isn't any Product for this ID let's skip the cycle if ( ! $adding_to_cart ) { continue; } $add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->get_type(), $adding_to_cart ); // Variable product handling if ( 'variable' === $add_to_cart_handler ) { woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_variable', $product_id ); // Grouped Products } elseif ( 'grouped' === $add_to_cart_handler ) { woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_grouped', $product_id ); // Custom Handler } elseif ( has_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler ) ){ do_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler, $url ); // Simple Products } else { woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_simple', $product_id ); } } } // Fire before the WC_Form_Handler::add_to_cart_action callback. add_action( 'wp_loaded', 'mm_add_to_cart_additional_products', 15 ); /** * Invoke class private method * * @since 0.1.0 * * @param string $class_name * @param string $methodName * * @return mixed */ function woo_hack_invoke_private_method( $class_name, $methodName ) { if ( version_compare( phpversion(), '5.3', '<' ) ) { throw new Exception( 'PHP version does not support ReflectionClass::setAccessible()', __LINE__ ); } $args = func_get_args(); unset( $args[0], $args[1] ); $reflection = new ReflectionClass( $class_name ); $method = $reflection->getMethod( $methodName ); $method->setAccessible( true ); $args = array_merge( array( $class_name ), $args ); return call_user_func_array( array( $method, 'invoke' ), $args ); } )或列表的字符串表示(visited_at)?

如果是列表,您可以使用[]

'[]'

如果是列表字符串,您可以使用以下方法进行破解:

apply

无论哪种方式,你都会得到:

visited_at.apply(lambda x: pd.to_datetime(x[0]) if len(x) else x)