datetime to decimal hour and minutes in python3

女生的网名这么多〃 提交于 2019-12-20 01:13:07

问题


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

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.


回答1:


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

There should be no need to convert to / from strings.

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')


来源:https://stackoverflow.com/questions/48992794/datetime-to-decimal-hour-and-minutes-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!