Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to time in Python

I have a large CSV-file with a column called TIME. It's written as 1318 and I would like to use Python/Pandas to convert the data as 13:18 and see it as time instead of int64.

I've tried something like this but this is not what I want:

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

Because I get this:

    1970-01-01 00:00:00.000001318                           
    1970-01-01 00:00:00.000001041                              
    1970-01-01 00:00:00.000000853

Any ideas?

like image 525
Donald Avatar asked May 06 '15 07:05

Donald


3 Answers

If you pass a format param to to_datetime you will get the following:

In [111]:

t="1318"
pd.to_datetime(t, format='%H%M')
Out[111]:
Timestamp('1900-01-01 13:18:00')

However, I don't know if you want a default date here.

like image 172
EdChum Avatar answered Nov 13 '22 21:11

EdChum


Use the format keyword argument to pd.to_datetime method.

It is a string with the usual strftime syntax.

like image 41
wim Avatar answered Nov 13 '22 21:11

wim


This might help:

  def extractTime(l):
    tt = (l.split(' ')[1]).split('.')[1][-4:];
    return tt[:2] + ':' + tt[-2:];

    if __name__ == '__main__':
      l = "1970-01-01 00:00:00.000001318";
      print extractTime(l);

It will print out "13:18" for the test case.

like image 2
Dan Avatar answered Nov 13 '22 19:11

Dan