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?
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?
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 .
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
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)
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