Thursday, March 29, 2018

Handling Date and Time in Pandas

First of all need to convert DataFrame Series to datetime object. You can start by importing the datetime module.

import datetime

You can check the column data type of any Pandas DF columns


It likely returns 'O' for object

In order to convert a column of type object to datetime use the pd.to_datetime function. You must also pass in a format specifying the year, month, day

df['col_name'] = pd.to_datetime(df['col_name'], format="%m/%d/%y")

This results in a datetime64 type column.

Formatting cheatsheet can be found here:
For more advanced datetime formatting, also refer to the official document above

Pandas can sometimes infer or guess the datetime without receiving format instructions
use this flag below

df['my_col'] = pd.to_datetime(df['my_col'], infer_datetime_format=True)

Once converted to datetime, we can access year month day  data:

No comments:

Post a Comment

Reinforcement Learning Q Learning

Explore <s, a> ---> s' reads: move from current state s to s' via action a.   Through the action a reward  is received, it ...