Links

Convert datetime series

Tags: #pandas #python #date #conversion #operations #snippet
Author: Florent Ravenel
Description: This notebook provides instructions on how to use the Pandas library to convert a datetime series into a usable format.

Input

Import library

import pandas as pd

Create Sample Dataframe

dict1 = {
"Name": ["Peter", "Dolly", "Maggie", "David", "Isabelle"],
"Date": ["20/2/2021", "19/8/2014", "8/9/2000", "4/3/2013", "14/7/1995"],
"Second Date": [
"August 20,2011",
"September 16,1993",
"January 23,2009",
"October 17,2019",
"March 4,2021",
],
}
df = pd.DataFrame(dict1)
df

Setup Variables

# Your date string format
current_format = "%d/%m/%Y"
# New date format you want to use
new_format = "%Y-W%U"

Model

Convert datetime string series to datetime series to another datetime string

df["New_Date"] = pd.to_datetime(df["Date"], format=current_format).dt.strftime(
new_format
)
df

Output

Display new dataframe

df