Home > front end >  After changing column type to string, hours, minutes and seconds are missing from the date
After changing column type to string, hours, minutes and seconds are missing from the date

Time:12-15

I am have a dataframe loaded from a file containing a time series and values

      datetime              value_a
0     2019-08-19 00:00:00   194.32000000
1     2019-08-20 00:00:00   202.24000000
2     2019-08-21 00:00:00   196.55000000
3     2019-08-22 00:00:00   187.45000000
4     2019-08-23 00:00:00   190.36000000 

After I try to convert first column to string, the hours minutes and seconds vanish.

     datetime     value_a
0    2019-08-19   194.32000000
1    2019-08-20   202.24000000
2    2019-08-21   196.55000000
3    2019-08-22   187.45000000
4    2019-08-23   190.36000000

Code snipped

df['datetime'] = df['datetime'].astype(str)

I kinda need the format %Y-%m-%d %H:%M:%S, because we are using it later.

What is wrong?

NOTE: I initially though that the issue is during conversion from object to datetime, however thanks to user @SomeDude, I have discovered that I am loosing h/m/s during to string conversion.

CodePudding user response:

It seems like the error can be fixed by using different type conversion method with explicit format definition.

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

This works.

CodePudding user response:

You're saying "I don't like the default format".

Ok. So be explicit, include HMS in it when you re-format.

>>> df = pd.DataFrame([dict(datetime='2019-08-19 00:00:00', value_a=194.32)])
>>> df['datetime'] = pd.to_datetime(df.datetime)
>>> 
>>> df['datetime'] = df.datetime.dt.strftime("%Y-%m-%d %H:%M:%S")
>>> df
              datetime  value_a
0  2019-08-19 00:00:00   194.32
  • Related