[英]Strings in nested lists
I have a list looking like this:我有一个看起来像这样的列表:
record1 = [["2020/02/19", 7.0], ["2020/02/20", 7.3], ["2020/02/21", 6.1]]
but I want to change the dates from yyyy/mm/dd
to dd/mm/yyyy
.但我想将日期从yyyy/mm/dd
更改为dd/mm/yyyy
。
record1= [["19/02/2020", 7.0], ["20/02/2020", 7,3], ["21/02/2020", 6.1]
How can I do this?我怎样才能做到这一点?
I cannot just use ::-1
because then everything gets mixed up.我不能只使用::-1
因为那样一切都会混淆。
The proper way of doing it using datetime
module:使用datetime
模块的正确方法:
record1 = [[datetime.strptime(d, '%Y/%m/%d').strftime('%d/%m/%Y'), v] for d, v in record1]
This converts it to datetime
object, then formats it the way you intended这会将其转换为datetime
时间 object,然后按照您想要的方式对其进行格式化
>>> record1
[['19/02/2020', 7.0], ['20/02/2020', 7.3], ['21/02/2020', 6.1]]
This would be a robust, explicit solution.这将是一个稳健、明确的解决方案。
But... Some experiments showed that manipulating strings with split
would be a faster solution:但是......一些实验表明,使用split
操作字符串将是一个更快的解决方案:
from datetime import datetime
import time
def convert_with_datetime(record1):
return [[datetime.strptime(d, '%Y/%m/%d').strftime('%d/%m/%Y'), v] for d, v in record1]
def convert_with_split(record1):
return [['/'.join(d.split('/')[::-1]), v] for d, v in record1]
record1 = [["2020/02/19", 7.0], ["2020/02/20", 7.3], ["2020/02/21", 6.1]] * 10**6
start = time.time()
convert_with_datetime(record1)
end = time.time()
print('convert_with_datetime:', end - start)
start = time.time()
convert_with_split(record1)
end = time.time()
print('convert_with_split:', end - start)
The result is:结果是:
convert_with_datetime: 12.311486959457397
convert_with_split: 1.3060288429260254
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.