如何使用python从csv中的同一列分割日期和时间?

时间:2017-02-09 01:25:29

标签: python date csv pandas datetime

我在csv文件中有第一列(PERIOD_START_TIME),包含日期和时间,但我需要将它们分成两个不同的列(日期,时间),所以我需要你的帮助......

PERIOD_START_TIME   
01.31.2017 13:00:00  
01.31.2017 14:00:00  
01.31.2017 15:00:00  
01.31.2017 16:00:00  
01.31.2017 17:00:00  
01.31.2017 18:00:00  
01.31.2017 19:00:00  
01.31.2017 20:00:00  
01.31.2017 21:00:00  
01.31.2017 22:00:00  
01.31.2017 23:00:00  
02.01.2017 00:00:00  
02.01.2017 01:00:00  
02.01.2017 02:00:00  
02.01.2017 03:00:00  

2 个答案:

答案 0 :(得分:1)

您的PERIOD_START_TIME可能不是datetime。确保它是。

df['PERIOD_START_TIME'] = pd.to_datetime(df['PERIOD_START_TIME'])

通过date访问者访问timedt属性。

df['date'] = df.PERIOD_START_TIME.dt.date
df['time'] = df.PERIOD_START_TIME.dt.time

print(df)

     PERIOD_START_TIME        date      time
0  2017-01-31 13:00:00  2017-01-31  13:00:00
1  2017-01-31 14:00:00  2017-01-31  14:00:00
2  2017-01-31 15:00:00  2017-01-31  15:00:00
3  2017-01-31 16:00:00  2017-01-31  16:00:00
4  2017-01-31 17:00:00  2017-01-31  17:00:00
5  2017-01-31 18:00:00  2017-01-31  18:00:00
6  2017-01-31 19:00:00  2017-01-31  19:00:00
7  2017-01-31 20:00:00  2017-01-31  20:00:00
8  2017-01-31 21:00:00  2017-01-31  21:00:00
9  2017-01-31 22:00:00  2017-01-31  22:00:00
10 2017-01-31 23:00:00  2017-01-31  23:00:00
11 2017-02-01 00:00:00  2017-02-01  00:00:00
12 2017-02-01 01:00:00  2017-02-01  01:00:00
13 2017-02-01 02:00:00  2017-02-01  02:00:00
14 2017-02-01 03:00:00  2017-02-01  03:00:00

设置

import pandas as pd
from io import StringIO

txt = """PERIOD_START_TIME
01.31.2017 13:00:00  
01.31.2017 14:00:00  
01.31.2017 15:00:00  
01.31.2017 16:00:00  
01.31.2017 17:00:00  
01.31.2017 18:00:00  
01.31.2017 19:00:00  
01.31.2017 20:00:00  
01.31.2017 21:00:00  
01.31.2017 22:00:00  
01.31.2017 23:00:00  
02.01.2017 00:00:00  
02.01.2017 01:00:00  
02.01.2017 02:00:00  
02.01.2017 03:00:00  """

df = pd.read_csv(StringIO(txt), parse_dates=[0])

答案 1 :(得分:0)

如果您需要在“DATE”和“TIME”列中拆分“PERIOD_START_TIME”列,我相信下面的代码会做(Python 3):

#!/usr/bin/env python3
# you may have to change "python3" to "python" depending on your setup.

import csv

# assuming your csv is separated by spaces, like the sample 
# also assuming that the the input file is named 'input.csv'
with open('input.csv', newline='') as csv_input: 
    csv_reader = csv.reader(csv_input, delimiter=' ')
    next(csv_reader)  # skips the header
    with open('output.csv', 'w', newline='') as csv_output:
        csv_writer = csv.writer(csv_output, delimiter=' ')
        csv_writer.writerow(['DATE', 'TIME'])
        for row in csv_reader:
            csv_writer.writerow([row[0], row[1]])