如何在python中将列中的多行从unicode更改为时间戳 [英] How to change multiple rows in a column from unicode to timestamp in python

查看:37
本文介绍了如何在python中将列中的多行从unicode更改为时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为初学者学习 Python.我想将列值从 unicode 时间 ('1383260400000') 转换为时间戳 (1970-01-01 00:00:01在此处输入代码).我已经阅读并尝试了以下内容,但它给了我一个错误.

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?

另一个,在同一个文件中,我有一些空单元格,我想用 0 替换,我也试过这个,但它给了我无效的语法:

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];如果 arr[3]='' :smsin='0';请帮忙.非常感谢.

推荐答案

您似乎忘记了 (arr[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

要将列表中的空字符串替换为0",您可以执行以下操作:

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']

请注意,后者只能正常工作,因为空字符串 '' 是唯一带有 真值.如果您在 arr 中有其他数据类型(例如 00L0.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]

更有效的是修改 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.

此外,您不需要将 ; 放在代码行的末尾,因为 Python 不需要它们终止语句.如果您希望将多个语句放在同一行,但在您的代码中并非如此,它们可用于分隔语句.

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.

这篇关于如何在python中将列中的多行从unicode更改为时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆