close

How to define format when using pandas to_datetime?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to define format when using pandas to_datetime in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to define format when using pandas to_datetime?

  1. How to define format when using pandas to_datetime?

    The format you are passing is invalid. The dash between the % and the I is not supposed to be there.

  2. define format when using pandas to_datetime

    The format you are passing is invalid. The dash between the % and the I is not supposed to be there.

Method 1

The format you are passing is invalid. The dash between the % and the I is not supposed to be there.

df['TIME'] = pd.to_datetime(df['TIME'], format="%m/%d/%Y %I:%M:%S %p")

This will convert your TIME column to a datetime.


Alternatively, you can adjust your read_csv call to do this:

pd.read_csv('testresult.csv', parse_dates=['TIME'], 
    date_parser=lambda x: pd.to_datetime(x, format='%m/%d/%Y %I:%M:%S %p'))

Again, this uses the appropriate format with out the extra -, but it also passes in the format to the date_parser parameter instead of having pandas attempt to guess it with the infer_datetime_format parameter.

Method 2

you can try this:

In [69]: df = pd.read_csv(fn, parse_dates=[0],
                          date_parser=lambda x: pd.to_datetime(x, format='%m/%d/%Y %I:%M:%S %p'))

In [70]: df
Out[70]:
                 TIME  RESULT
0 2016-03-24 00:27:11       2
1 2016-03-24 00:28:41      76
2 2016-03-24 00:37:23      19
3 2016-03-24 00:38:44      68
4 2016-03-24 00:42:02      44

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read