Convert string date to pandas datetime

I am new to Pandas and Python. I want to do some date operations in my script. I get the time information from the csv file in the following format:   01APR2017 6:59

How to convert it to Pandas datetime format? Something like: 2017-04-01 06:59:00

+4
source share
1 answer

You can use to_datetimewith parameter format:

s = pd.Series(['01APR2017 6:59','01APR2017 6:59'])

print (s)
0    01APR2017 6:59
1    01APR2017 6:59
dtype: object

print (pd.to_datetime(s, format='%d%b%Y %H:%M'))
0   2017-04-01 06:59:00
1   2017-04-01 06:59:00
dtype: datetime64[ns]

Another possible solution is to use date_parserin read_csv:

import pandas as pd
from pandas.compat import StringIO

temp=u"""date
01APR2017 6:59
01APR2017 6:59"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
parser = lambda x: pd.datetime.strptime(x, '%d%b%Y %H:%M')
df = pd.read_csv(StringIO(temp), parse_dates=[0], date_parser=parser)

print (df)
                 date
0 2017-04-01 06:59:00
1 2017-04-01 06:59:00

print (df.date.dtype)
datetime64[ns]

EDIT by comments:

datetime, errors='coerce' NaT:

s = pd.Series(['01APR2017 6:59','01APR2017 6:59', 'a'])
print (s)
0    01APR2017 6:59
1    01APR2017 6:59
2                 a
dtype: object

print (pd.to_datetime(s, format='%d%b%Y %H:%M', errors='coerce'))
0   2017-04-01 06:59:00
1   2017-04-01 06:59:00
2                   NaT
dtype: datetime64[ns]
+8

Source: https://habr.com/ru/post/1665965/


All Articles