1

I would like to convert the following time format which is located in a panda dataframe column

100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000
2100
2200
2300
2400

I would like to transform the previous time format into a standard time format of HH:MM as follow

01:00
02:00
03:00
...
15:00
16:00
...
22:00
23:00
00:00

How can I do it in python?

Thank you in advance

azro
  • 53,056
  • 7
  • 34
  • 70
  • Does this answer your question? [Fastest way to parse a column to datetime in pandas](https://stackoverflow.com/questions/50507468/fastest-way-to-parse-a-column-to-datetime-in-pandas) – azro Apr 05 '20 at 20:45
  • Something like `df['col2'] = pd.to_datetime(df['col1'],format='%H%M')` – azro Apr 05 '20 at 20:45
  • Thank you for your reply. I does not work since the tricky part is the 2400 hour format. I would like to change that format into 00:00. – José R. Valles León Apr 06 '20 at 22:01

1 Answers1

0

This will give you a df with a datetime64[ns] and object dtype column for your data:

import pandas as pd

df = pd.read_csv('hm.txt', sep=r"[ ]{2,}", engine='python', header=None, names=['pre'])

df['pre_1'] = df['pre'].astype(str).str.replace('00', '')

df['datetime_dtype'] = pd.to_datetime(df['pre_1'], format='%H', exact=False)

df['str_dtype'] = df['datetime_dtype'].astype(str).str[11:16]

print(df.head(5))

    pre datetime_dtype  str_dtype
0   1   1900-01-01 01:00:00 01:00
1   2   1900-01-01 02:00:00 02:00
2   3   1900-01-01 03:00:00 03:00
3   4   1900-01-01 04:00:00 04:00
4   5   1900-01-01 05:00:00 05:00 

print(df.dtypes)

pre                       object
datetime_dtype    datetime64[ns]
str_dtype                 object
dtype: object
Matthew Borish
  • 3,016
  • 2
  • 13
  • 25