Python从日期时间列表中获取一个月中第一天的列表

时间:2016-01-12 15:18:27

标签: python datetime

我有一个列表'A',其内容是datetime.datetime。

我想获得另一个列表或数组'B',它存储列表A中每个日期时间的第一天。

我想获得另一个列表或数组'C',它只存储A中每个日期时间的月份数。

除了使用for循环之外,是否有可能以更智能的方式实现这一目标。我已经完成了代码,但我可以自由地将A,B,C更改为列表或数组等,因为它适合我。

date_format     =   "%m/%d/%Y"
st_dt   =   datetime.strptime( '02/01/2016', date_format )
en_dt   =   datetime.strptime( '03/31/2016', date_format )
A = [ st_dt + timedelta( days = x ) for x in range( ( en_dt - st_dt ).days + 1 ) ]

编辑: 第一天意味着第一天,例如如果日期是2016年2月15日,那么我的案件的第一个日期将是2/1/2016

1 个答案:

答案 0 :(得分:1)

使用pandas

dts = [datetime(2016,2,1), datetime(2016,3,31)]

import pandas as pd

a = pd.DatetimeIndex(dts)

# a: <class 'pandas.tseries.index.DatetimeIndex'>
#    [2016-02-01, 2016-03-31]
#    Length: 2, Freq: None, Timezone: None


# b stores the first day of month for each of the datetime in the list a.

b = a.map(lambda x: x.replace(day=1))

# b: array([Timestamp('2016-02-01 00:00:00'),
#           Timestamp('2016-03-01 00:00:00')], dtype=object)


# c stores just the month number for each datetime in a.

c = a.month

# c: array([2, 3], dtype=int32)