繁体   English   中英

Python:日期时间的整数列表?

[英]Python: List of integers to datetime?

我有一个列表[14,9,11,2,1,21] ,我想在日期时间对象中对其进行转换(例如2014/09/11 02:01:21

>>> from datetime import datetime
>>> x = [14,9,11,2,1,21]
>>> datetime(x)
TypeError: an integer is required

v像这样的东西行得通,但是显然不是正确的解决方法:

>>> datetime(x[0], x[1], x[2], x[3], x[4], x[5], x[6])

我应该怎么做?

这不是理想的方法,但是您可以在“ year”(年份)中加上2000之后再打开包装(否则,您将以14年结束),例如:

from datetime import datetime

x = [14,9,11,2,1,21]
x[0] += 2000
dt = datetime(*x)
# 2014-09-11 02:01:21

您需要扩展列表x包含的参数:

x = [14,9,11,2,1,21]
dt = datetime(x[0]+2000, *x[1:])  # The star expands the remaining integers into arguments for datetime()
# 2014-09-11 02:01:21

该解决方案的优点是比Jon更直接,并且不修改输入列表(这使它更通用)。

PS:如果您需要在中间修改一个值(例如第三个值),那么这将更加复杂,在这种情况下,乔恩的答案可能更清晰:

other_function(*(x[:2] + [x[2]+2000] + x[3:]))  # A new list is first created with the modified arguments

添加到Eric Lebigots 答案中 ,您可以在列表推导中使用枚举来定位多个索引。 这也不会修改输入列表。

例如,如果您想为年份增加2000,并且由于某种原因还希望增加12小时:

datetime(*[n+2000 if y == 0 else n+12 if y == 3 else n for y,n in enumerate([14,9,11,2,1,21])])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM