Home > Blockchain >  Date format conversion to text (yyyymmdd)
Date format conversion to text (yyyymmdd)

Time:11-29

I have a date in format of YYYY-MM-DD (2022-11-01). I want to convert it to 'YYYYMMDD' format (without hyphen). Pls support.

I tried this...

df['ConvertedDate']= df['DateOfBirth'].dt.strftime('%m/%d/%Y')... but no luck

CodePudding user response:

If I understand correctly, the format mask you should be using with strftime is %Y%m%d:

df["ConvertedDate"] = df["DateOfBirth"].dt.strftime('%Y%m%d')

CodePudding user response:

This works

from datetime import datetime 

initial = "2022-11-01"
time = datetime.strptime(initial, "%Y-%m-%d")
print(time.strftime("%Y%m%d"))

CodePudding user response:

Pandas itself providing the ability to convert strings to datetime in Pandas dataFrame with desire format.

df['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')

Referenced Example:

import pandas as pd

values = {'DateOfBirth': ['2021-01-14', '2022-11-01', '2022-11-01']}

df = pd.DataFrame(values)
df['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')

print (df)

Output:

  DateOfBirth ConvertedDate
0  2021-01-14      20210114
1  2022-11-01      20221101
2  2022-11-01      20221101
  • Related