How to change multiple rows in a column from unico

2019-09-04 07:45发布

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 tried the following but its giving me an error.

ti=datetime.datetime.utcfromtimestamp(int(arr[1]).strftime('%Y-%m-%d %H:%M:%S');

Its saying invalid syntax. I read and tried a few other stuffs but I can not come right.. Any suggestion?

And another one, in the same file I have some empty cells that I would like to replace with 0, I tried this too and its giving me invalid syntax:

smsin=arr[3]; if arr[3]='' : smsin='0'; Please help. Thank you alot.

1条回答
时光不老,我们不散
2楼-- · 2019-09-04 08:31

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):
    if item = '':
        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.

查看更多
登录 后发表回答