python-将日期和时间与列表中的日期时间元素分开
作者:互联网
我有一个列表,每个列表包含3个元素,其中一个是datetime.我需要修改列表,以将日期和时间分成各自的元素,然后将它们放回列表中.
输入样例:
[[2, 13, '2019-02-02T07:00:00'], [7, 8, '2019-02-02T09:00:00']]
所需的输出:
[[2, 13, '2019-02-02', '07:00'], [7, 8, '2019-02-02', '09:00']]
我可以使用下面的代码隔离时间或日期,但无法弄清楚如何获取两者:
from datetime import datetime
data_set_x = [[2, 13, '2019-02-02T07:00:00'], [7, 8, '2019-02-02T09:00:00']]
def convert_date(s):
date_object = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
return date_object.strftime('%Y-%m-%d')
for idx,item in enumerate(data_set_x):
data_set_x[idx][-1] = convert_date(item[2])
for i in data_set_x:
sql = "insert into data (ValueA, ValueB, Date) values (%s, %s, %s)"
print(sql, i)
解决方法:
from datetime import datetime
data_set_x = [[2, 13, '2019-02-02T07:00:00'], [7, 8, '2019-02-02T09:00:00']]
def convert_date(s):
date_object = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
return date_object.strftime('%Y-%m-%d'), date_object.strftime('%H:%M')
for idx,item in enumerate(data_set_x):
data_set_x[idx][-1], time = convert_date(item[2])
data_set_x[idx].append(time)
for i in data_set_x:
sql = "insert into data (ValueA, ValueB, Date, Time) values (%s, %s, %s, %s)"
print(sql, i)
标签:python-3-x,python 来源: https://codeday.me/bug/20191211/2106746.html