0

I have a column in my dataframe in the format : 15-Feb-2020 19:09:34

and

I want to convert it into : 2020-02-15 ie YYYY-MM-DD using python.

Is there a way of doing this using datetime or any other python module?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
rylp
  • 111
  • 1
  • 6

4 Answers4

1

Use the to_datetime pandas function.

Like this, maybe:

import pandas as pd
#if DATE is the column with datetime values then
df['DATE'] = pd.to_datetime(df['DATE'])

This will convert the column to the form of YYYY-MM-DD .

Costa
  • 472
  • 4
  • 6
0

You can use to_datetime function and after conversion choose only date

In [12]: df
Out[12]:
                   Date
0  15-Feb-2020 19:09:34

In [13]: df['new_date'] = pd.to_datetime(df['Date']).dt.date

In [14]: df
Out[14]:
                   Date    new_date
0  15-Feb-2020 19:09:34  2020-02-15

bigbounty
  • 16,526
  • 5
  • 37
  • 65
0

You can use python's datetime module to format.

from datetime import datetime

#current date and time
now = datetime.now()
#date and time format: dd/mm/YYYY H:M:S
format = "%d/%m/%Y %H:%M:%S"
#format datetime using strftime()
time1 = now.strftime(format)

print("Formatted DateTime:", time1)
Uzair
  • 1
  • 1
  • 3
0

You can convert a date string to another one by parsing and reformating as below.

from datetime import datetime

date = datetime.strptime('15-Feb-2020 19:09:34', '%d-%b-%Y %H:%M:%S')

print(date.strftime('%Y-%m-%d'))

You can find related format codes here: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

Taha Metin Bayi
  • 201
  • 1
  • 8