简体   繁体   English

Python3.8:组合两个日期时间变量

[英]Python3.8: combine two datetime variables

I have the following code我有以下代码

import datetime
Date_0 = [datetime.date(2021,3,10), datetime.date(2021,3,11)]
Date_1 = datetime.date(2021,3,12)
Date_combine = [Date_0, Date_1]

I got the result of Data_combine: [[2021-03-10, 2021-03-11], 2021-03-12] But I want to get this: [2021-03-10, 2021-03-11, 2021-03-12]我得到了 Data_combine 的结果: [[2021-03-10, 2021-03-11], 2021-03-12] 但我想得到这个: [2021-03-10, 2021-03-11, 2021- 03-12]

How could I achieve this?我怎么能做到这一点? Thank you!谢谢!

Just make a new list that unpacks the existing list and adds on the new element:只需创建一个新list ,将现有list解包并添加新元素:

Date_combine = [*Date_0, Date_1]

The * says "unpack the contents of Date_0 here without the wrapping" (see PEP 448 for details). *表示“在此处解压缩Date_0的内容而不进行包装”(有关详细信息,请参阅PEP 448 )。 Put * s before any element that is itself a list or other iterable and you want to include the contents of, leave it off for the values you want to include as themselves, without unpacking.* s 放在本身是list或其他可迭代的任何元素之前,并且您想要包含其内容,将其保留为您想要包含为自身的值,无需解包。

On older Python (pre-3.5), you could use concatenation for a simple case like this, by wrapping the non- list elements in temporary list s eg:在较旧的 Python(3.5 之前)上,您可以通过将非list元素包装在临时list中来将连接用于这样的简单情况,例如:

Date_combine = Date_0 + [Date_1]

or if you don't need it to be a new list , and modifying Date_0 in place is fine, the even simpler:或者如果你不需要它是一个list ,并且修改Date_0就可以了,那就更简单了:

Date_0.append(Date_1)

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

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