Changing datetime format which includes weekday?

Viewed 319

Currently I have datetime column in this format

        Datime
        Thu Jun 18 23:04:19 +0000 2020
        Thu Jun 18 23:04:18 +0000 2020
        Thu Jun 18 23:04:14 +0000 2020
        Thu Jun 18 23:04:13 +0000 2020

I want to change it to:

   Datetime
 2020-06-18 23:04:19
 2020-06-18 23:04:18
 2020-06-18 23:04:14
 2020-06-18 23:04:13
2 Answers

Assuming you have loaded your pandas dataframe, you can convert Datetime column to specified format using this function. You can rename this function.

import datetime

def modify_datetime(dtime):
    my_time = datetime.datetime.strptime(dtime, '%a %b %d %H:%M:%S %z %Y')
    return my_time.strftime('%Y-%m-%d %H:%M:%S')

First argument to strptime function is date string and second argument is format.

Directive, Description

%a         Weekday abbreviated
%b         Month abbreviated name
%d         Day of the month
%H         Hour (24-hour format)
%M         Minute with zero padding
%S         Second with zero padding
%z         UTC offset
%Y         Full year

Once you converted string date to datetime objects you can convert it back to string with specified format using strftime function. You can read more about formats here.

Finally, just modify the Datetime column

df['Datetime'] = df['Datetime'].apply(modify_datetime)

You can use pandas.to_datetime and pandas.Series.dt.strftime appropriately:

>>> import pandas as pd
>>> from datetime import datetime
>>> datetime_strs = ["Thu Jun 18 23:04:19 +0000 2020", "Thu Jun 18 23:04:18 +0000 2020", "Thu Jun 18 23:04:14 +0000 2020", "Thu Jun 18 23:04:13 +0000 2020"]
>>> d = {'Datetimes': datetime_strs}
>>> df = pd.DataFrame(data=d)
>>> df
                        Datetimes
0  Thu Jun 18 23:04:19 +0000 2020
1  Thu Jun 18 23:04:18 +0000 2020
2  Thu Jun 18 23:04:14 +0000 2020
3  Thu Jun 18 23:04:13 +0000 2020
>>> df['Datetimes'] = pd.to_datetime(df['Datetimes'], format='%a %b %d %H:%M:%S %z %Y')
>>> df
                  Datetimes
0 2020-06-18 23:04:19+00:00
1 2020-06-18 23:04:18+00:00
2 2020-06-18 23:04:14+00:00
3 2020-06-18 23:04:13+00:00
>>> df['Datetimes'] = df['Datetimes'].dt.strftime('%Y-%m-%d %H:%M:%S')
>>> df
             Datetimes
0  2020-06-18 23:04:19
1  2020-06-18 23:04:18
2  2020-06-18 23:04:14
3  2020-06-18 23:04:13
Related