how do I convert this datetime columns to the same format?

Viewed 44

Consider this portion of a dataframe I am working with:

df = pd.DataFrame({
't1': ['2016-04-13 14:21:20+01:00', '2016-04-20 12:46:50+01:00', '2016-04-27 07:32:32+01:00'],
't2': ['2016-04-13 15:37:08.943+01', '2016-04-20 12:54:53.082+01', '2016-04-27 07:45:41.649+01']
})

df
                 t1                           t2
0   2016-04-13 14:21:20+01:00   2016-04-13 15:37:08.943+01
1   2016-04-20 12:46:50+01:00   2016-04-20 12:54:53.082+01
2   2016-04-27 07:32:32+01:00   2016-04-27 07:45:41.649+01

t2 has second fractions, t1 has none. I converted both to pandas datetime:

df["t1"] = pd.to_datetime(df["t1"], utc=True)
df['t1'] = df['t1'].dt.tz_localize(None)

df["t2"] = pd.to_datetime(df["t2"], utc=True)
df['t2'] = df['t2'].dt.tz_localize(None)

So:

                t1                  t2
0   2016-04-13 13:21:20 2016-04-13 14:37:08.943
1   2016-04-20 11:46:50 2016-04-20 11:54:53.082
2   2016-04-27 06:32:32 2016-04-27 06:45:41.649

How do I transform t2 to drop those fractions, so that it appears like t1?

1 Answers

One can use pandas.Series.dt.strftime as follows

df['t2'] = df['t2'].dt.strftime('%Y-%m-%d %H:%M:%S')

[Out]:
                   t1                   t2
0 2016-04-13 13:21:20  2016-04-13 14:37:08
1 2016-04-20 11:46:50  2016-04-20 11:54:53
2 2016-04-27 06:32:32  2016-04-27 06:45:41

This method supports the same string format as the python standard library. (Source)

So here we will be able to see the various format codes.

Related