简体   繁体   中英

Parsing year, month, day, hour, minute, second in Python

I have a csv file with headers and they are: year, month, day, hour, minute, second, firstName

I have the following code in Python:

import pandas as pd
from datetime import datetime
parse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv('filename.csv',  
           parse_dates={'Date/Time': ['year', 'month', 'day', 'hour', 'minute', 'second']}, 
            index_col=0)
df[:5]

When the table is shown the Date/Time column shows as

Date/Time
2013 6 26 18 57 22

instead of

Date/Time
2013-6-26 18:57:22

Any help would be appreciated. Thank you.

Change your parser and use it like this:

import pandas as pd
from datetime import datetime

def parse(year, month, day, hour, minute, second):
    return year+ '-' +month+ '-' +day+ ' ' +hour+ ':' +minute+ ':' +second

df = pd.read_csv('test.csv', parse_dates={'Date/Time':['year', 'month', 'day', 'hour', 'minute', 'second']}, 
           date_parser=parse,
           index_col=0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM