Giladbi
Giladbi

Reputation: 1894

how to convert column to time with milliseconds?

I have the following txt file with 2 columns:

Date, Time
2013/1/4, 07:00:00.0
2013/1/4, 07:00:00.1
2013/1/4, 07:00:00.2
2013/1/4, 07:00:00.3
2013/1/4, 07:00:00.4
2013/1/4, 07:00:00.5
2013/1/4, 07:00:00.6
2013/1/4, 07:00:00.7
2013/1/4, 07:00:00.8
2013/1/4, 07:00:00.9
2013/1/4, 07:00:00.10
2013/1/4, 07:00:00.11
2013/1/4, 07:00:00.12
2013/1/4, 07:00:00.13
2013/1/4, 07:00:00.14
2013/1/4, 07:00:00.15
2013/1/4, 07:00:00.16

I need to convert the object into time format. For the "date" used (and it's working as expected):

df['Date'] = pd.to_datetime(df['Date'])

For the "time" I used to following (all failed, and yes I tried to search out and read pandas documentation)

df['Time']= (pd.to_datetime(df['Time'].str.strip(), format='%H:%M:%S:%F'))
df['Time'] = datetime.time(df['Time'], '%H:%M:%S,%f')
df['Time'] = datetime.datetime.strptime("%H:%M:%S,%f").timestamp()

even tried this:

df['DateTime'] = pd.to_datetime(df.pop('Date')) + pd.to_timedelta(df.pop('Time'))

Please advice what have I done wrong here in order to complete the time foramt. Your help is much appreciated!

Upvotes: 1

Views: 242

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76317

It is probably simpler to concatenate the columns as strings, turn them into date/time objects, and then manipulate them further (if needed).

For your data, the following works for me:

pd.to_datetime(df.Date + ' ' + df.Time)

(Note that df.Date + ' ' + df.Time makes a string series in a format that pandas understands, in your case.)

To get the hour, for example:

df['foo'] = pd.to_datetime(df.Date + ' ' + df.Time)
df.foo.dt.hour

Upvotes: 1

Related Questions