How to change multiple rows in a column from unicode to timestamp in python

笑着哭i 提交于 2019-12-12 03:44:09

问题


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:


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.



来源:https://stackoverflow.com/questions/37363733/how-to-change-multiple-rows-in-a-column-from-unicode-to-timestamp-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!