Skip to content Skip to sidebar Skip to footer

How To Change Multiple Rows In A Column From Unicode To Timestamp In Python

I am learning python for beginners. I would like to convert column values from unicode time ('1383260400000') to timestamp (1970-01-01 00:00:01enter code here). I have read and tri

Solution 1:

You seem to have forgotten a closing bracket after (arr[1]).

import datetime

arr = ['23423423', '1163838603', '1263838603', '1463838603']
ti = datetime.datetime.utcfromtimestamp(int(arr[1])).strftime('%Y-%m-%d %H:%M:%S')

print(ti)
# => 2006-11-18 08:30:03

To replace empty strings with '0's in your list you could do:

arr = ['123', '456', '', '789', '']
arr = [x if x else'0'for x in arr]

print(arr)
# => ['123', '456', '0', '789', '0']

Note that the latter only works correctly since the empty string '' is the only string with a truth value of False. If you had other data types within arr (e.g. 0, 0L, 0.0, (), [], ...) and only wanted to replace the empty strings you would have to do:

arr = [x if x != '' else '0' for x in arr]

More efficient yet would be to modify arr in place instead of recreating the whole list.

for index, item in enumerate(arr):
    ifitem='':
        arr[index] = '0'

But if that is not an issue (e.g. your list is not too large) I would prefer the former (more readable) way.

Also you don't need to put ;s at the end of your code lines as Python does not require them to terminate statements. They can be used to delimit statements if you wish to put multiple statements on the same line but that is not the case in your code.

Post a Comment for "How To Change Multiple Rows In A Column From Unicode To Timestamp In Python"