Home > Back-end >  Issue while converting pandas to datetime
Issue while converting pandas to datetime

Time:08-05

I'm converting string to datetime datatype using pandas, here is my snippet,

df[col] = pd.to_datetime(df[col], format='%H%M%S%d%m%Y', errors='coerce')

input :

col
00000001011970
00000001011970
...
00000001011970

output:

col
1970-01-01
1970-01-01
...
1970-01-01 00:00:00

the ouput consists of date and date with time.. I need the output as date with time. PLease help me out where I am going wrong

CodePudding user response:

The time is there. It just so happens, because it's midnight, 00:00:00, it is not showing explicitly.

You can see it's with e.g.

df[col].dt.minute

which will give a Series of 0's.

To print out the time explicitly, you could use

df[col].dt.strftime('%H:%M:%S')

Alter the format as you see fit.


Keep in mind that the visual output with anything in Pandas (or computers in general) does not have to be exactly what is stored. It is up to the programmer to format the output into what they want. But calculations on the variables still uses all (invisible) information.

CodePudding user response:

Just like the other answer suggested time is there, but since it's midnight 00:00:00, it's not showing explicitly. To print out the date with time you can try this :

df[col] = pd.to_datetime(df[col], format='%H%M%S%d%m%Y', errors='coerce').dt.strftime('%Y-%m-%d %H:%M:%S')
  • Related