本文介绍了日期时间到python3中的十进制小时和分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧,每 30分钟就有一个气象数据数据。使用我的datetime索引,我需要创建一个带有 timestamps 的列,但是它必须为 decimal 。下面是示例:

I have a dataframe with meteorological data every 30 minutes. With my datetime index I need to create a column with timestamps, but it must be in decimal. Here's the example below:

In [134]: df.index[0:3]
Out[134]: 
DatetimeIndex(['2016-01-01 00:30:00', '2016-01-01 01:00:00',
               '2016-01-01 01:30:00'],
              dtype='datetime64[ns]', name='date_time', freq=None)

我需要创建一个列,如下所示:

I need create a column as follows:

df.new[0:3]
0.5,1,1.5

哪里有30分钟我转换为 .5
遵循我的脚本:

Where have 30 minutes i transform in .5 .Follow my script:

import pandas as pd
import numpy as np
df = pd.read_csv('./cs_teste_full_output_2018-02-26T004329_adv.csv',skiprows=(0),
                 header=1,na_values='-9999.0')
df = df.drop(df.index[[0]])
df['date_time'] = df['date'] + str(' ') + df['time']
df = df.set_index(pd.DatetimeIndex(df['date_time']))


df.index.strftime('%M')/60

for i in range(1,len(df.index),1):
    print(i)
    df['minute'][i] = np.array(list(map(int,list(df.index.strftime('%M')))))/60
    df['hour'] = df.index.strftime('%H')
    df['hour_minute'] = df['hour'] + df['minute']

但是这种方式不起作用,我无法用其他任何方式

But this way it is not working and I can not do it any other way.

推荐答案

一种方法是提取小时并将分钟转换为小时。

One way is to extract the hour and convert minutes to hours.

无需转换为字符串。

import pandas as pd

idx = pd.DatetimeIndex(['2016-01-01 00:30:00',
                        '2016-01-01 01:00:00',
                        '2016-01-01 01:30:00'],
                       dtype='datetime64[ns]', name='date_time', freq=None)

idx.hour + idx.minute / 60

# Float64Index([0.5, 1.0, 1.5], dtype='float64', name='date_time')

这篇关于日期时间到python3中的十进制小时和分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 23:57