MxGr20
MxGr20

Reputation: 77

Convert datetime64 to integer hours using Python

I have the following dataframe

        Timestamp           KE          EH  LA       PR
0       2013-02-27 00:00:00 1.000000    2.0 0.03    201.289993
1       2013-02-27 00:15:00 0.990000    2.0 0.03    210.070007
2       2013-02-27 00:30:00 0.950000    2.0 0.02    207.779999
3       2013-02-27 00:45:00 0.990000    2.0 0.03    151.960007
4       2013-02-27 01:00:00 341.209991  2.0 0.04    0.000000
... ... ... ... ... ...
3449    2013-04-03 22:15:00 NaN         2.0 0.03    0.000000
3450    2013-04-03 22:30:00 NaN         NaN 0.07    0.000000

I would like to turn the timestamp column into a numeric value while keeping only the 'time' like illustrated below

        Timestamp           KE          EH  LA       PR
0       0                   1.000000    2.0 0.03    201.289993
1       15                  0.990000    2.0 0.03    210.070007
2       30                  0.950000    2.0 0.02    207.779999
3       45                  0.990000    2.0 0.03    151.960007
4       100                 341.209991  2.0 0.04    0.000000
... ... ... ... ... ...
3449    2215                NaN         2.0 0.03    0.000000
3450    2230                NaN         NaN 0.07    0.000000

I tried the code below based on this post[enter link description here][1]

h3_hours["Timestamp"] = h3_hours["Timestamp"].astype(str).astype(int)

But this gives me the error below

ValueError: invalid literal for int() with base 10: '2013-02-27 00:00:00'

Then I found online this approach

# Turn datetime into hours and minutes
h3_hours["Timestamp"] = h3_hours["Timestamp"].dt.strftime("%H:%M")

h3_hours["Timestamp"] = h3_hours["Timestamp"].astype(int)

But this gives me the same error as above.

Any idea on how I can turn my Timestamp column into integer hours? [1]: Pandas: convert dtype 'object' to int

Upvotes: 1

Views: 584

Answers (1)

jezrael
jezrael

Reputation: 863531

You are close, need remove : in %H%M for HHMM format:

h3_hours["Timestamp"] = h3_hours["Timestamp"].dt.strftime("%H%M").astype(int)

Upvotes: 2

Related Questions