Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Change dates in dataframe to same date format

Tags:

python

pandas

I have a dataframe that contains a column which holds:

Date:
31MAR2005
30-06-05
311205

I would like to convert these dates to the format : 30-06-05 (DD-MM-JJ). What is the simplest way to do this? The fields are not in a date format yet, only strings.

like image 213
F1990 Avatar asked Feb 15 '26 01:02

F1990


1 Answers

Here is my example :

def string_to_date(my_string):
    if '-' in my_string:
        return datetime.datetime.strptime(my_string, '%d-%m-%y')
    elif my_string.isdigit():
        return datetime.datetime.strptime(my_string, '%d%m%y')
    elif my_string.isalnum():
        return datetime.datetime.strptime(my_string, '%d%b%Y')

now I'm testing it on your dataframe df :

In[116]: df['Date:'].apply(lambda x: string_to_date(x))
Out[114]: 
0   2005-03-31
1   2005-06-30
2   2005-12-31
Name: Date:, dtype: datetime64[ns]
like image 64
Alex Avatar answered Feb 16 '26 13:02

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!