简体   繁体   English

Pandas 中的日期时间

[英]Datetime in Pandas

I have a data frame similar to the following:我有一个类似于以下的数据框:

--------------------------------------------------------------------------------------
| Start_Date       |  End_Date         | Jan-16 | Feb-16 | Mar-16 | Apr-16 | May-16   |
| 2016-02-20 17:40 |  2019-11-20 16:31 |  0     | 1      | 1      | 1      | 1        |
| 2016-03-11 15:12 |  2020-11-01 12:12 |  0     | 0      | 1      | 1      | 1        |
---------------------------------------------------------------------------------------

If the start and end date fall in between January 2016 to December 2020, I need to put a 1 or else a 0 using PANDAS in the respective month column.如果开始和结束日期在 2016 年 1 月到 2020 年 12 月之间,我需要在相应的月份列中使用 PANDAS 输入 1 或 0。 For example, in the first row, the date is Feb 20, 2020. Therefore, there is a 0 in the Jan-16 column and 1 in Feb-16, Mar-16, Apr-16 and so on.例如,在第一行中,日期为 2020 年 2 月 20 日。因此,1 月 16 日列中有 0,2 月 16 日、3 月 16 日、16 年 4 月等列中有 1。 Date is in Year, Month and Day format.日期采用年、月和日格式。

How do you achieve this?你如何做到这一点?

If you are trying to count how many months occur between the start and end date,如果您要计算开始日期和结束日期之间的月份数,

import datetime
start_date = datetime.datetime.strptime('2016-02-20 17:40', '%Y-%m-%d %H:%M')
end_date = datetime.datetime.strptime('2019-11-20 16:31', '%Y-%m-%d %H:%M')
num_months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)

num_months print(num_months) num_months 打印(num_months)

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

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