pythondumb
pythondumb

Reputation: 1247

Python: Convert a date and time into integers

I want to convert the following pandas time stamp column into float32.

I have filled up the Date, Time by the codes as given below

 TimeStamp           Date           Time     Day     Time    float32
04-01-2019 21:58    04-01-2019    21:58:33                           
04-01-2019 20:23    04-01-2019    20:23:06
31-12-2018 19:26    31-12-2018    19:26:11

For Date and Time I have used the following codes in pandas

df['Date'] = pd.to_datetime(df['TimeStamp']).dt.date
df['Time'] = pd.to_datetime(df['TimeStamp']).dt.time

Now what I want is how to populate Day and Time.

Besides, how can I convert Date / or TimeStamp to float32.

Upvotes: 0

Views: 308

Answers (2)

Mohit Motwani
Mohit Motwani

Reputation: 4792

You can use:

df = pd.DataFrame({'TimeStamp':['04-01-2019 21:58', '04-01-2019 20:23', '31-12-2018 19:26'] })
df['TimeStamp'] = pd.to_datetime(df['TimeStamp'])
df['Date'] = df['TimeStamp'].dt.date
df['Time'] = df['TimeStamp'].dt.time
df['Day'] = df['TimeStamp'].dt.day
df['time_float'] = (df['TimeStamp'].astype('int64')//1e9).astype('float32')
df


    TimeStamp            Date        Time      Day  time_float
0   2019-04-01 21:58:00 2019-04-01  21:58:00    1   1.554156e+09
1   2019-04-01 20:23:00 2019-04-01  20:23:00    1   1.554150e+09
2   2018-12-31 19:26:00 2018-12-31  19:26:00    31  1.546284e+09

Upvotes: 2

Serena
Serena

Reputation: 67

Probably try this?

import time
import numpy as np
t = time.time(Date) # or Time
results = np.float32(t)

Upvotes: 0

Related Questions