Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert multiple date formats in one format in pandas

Tags:

python

pandas

I have following pandas dataframe with date column as object

   ID      Date                  Volume
   0       13-02-2018 00:06       85
   1       13-02-2018 00:10       70
   2       13-02-2018 00:11       100
   3       2018-02-13 06:30       123
   4       02-13-2018 07:56       100

I want to convert it to following one format

   ID      Date                  Volume
   0       2018-02-13 00:06       85
   1       2018-02-13 00:10       70
   2       2018-02-13 00:11       100
   3       2018-02-13 06:30       123
   4       2018-02-13 07:56       100

I am trying to achieve this by following command

df['Date'] = df.date.apply(lambda x: pd.to_datetime(x).strftime('%Y-%m-%d %H:%M')[0])

But it throws an error. How can I do it in pandas?

like image 315
Neil Avatar asked Aug 10 '18 07:08

Neil


People also ask

How do I change the date format in a DataFrame in Python?

Function usedstrftime() can change the date format in python.

Can pandas DataFrame hold different types?

A DataFrame is a 2-dimensional data structure that can store data of different types (including characters, integers, floating point values, categorical data and more) in columns.

Can a DataFrame have multiple data types?

A column in a DataFrame can only have one data type. The data type in a DataFrame's single column can be checked using dtype . Make conscious decisions about how to manage missing data.

How do I change date format to MM DD YYYY in pandas?

Please notice that you can also specify the output date format other than the default one, by using the dt. strftime() method. For example, you can choose to display the output date as MM/DD/YYYY by specifying dt. strftime('%m/%d/%Y') .


1 Answers

try this:

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

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d %H:%M')

link: Series.dt.strftime

like image 72
Nihal Avatar answered Oct 05 '22 23:10

Nihal