2

I am trying to obtain the first day of month from array of datetime i.e. change all days to 1 and all hours to 0:

import pandas as pd
z1 = [datetime(2025, 10, 1, 3, 0),datetime(2025, 1, 6, 7, 0)]
pd.DatetimeIndex(z1).normalize()
DatetimeIndex(['2025-10-01', '2025-01-06'], dtype='datetime64[ns]', freq=None)

I was hoping to achieve

DatetimeIndex(['2025-10-01', '2025-01-01'], dtype='datetime64[ns]', freq=None)

3 Answers 3

4

Another way would be to form a NumPy array of dtype datetime64[M] (a datetime64 with monthly resolution)

In [31]: np.array(z1, dtype='datetime64[M]')
Out[31]: array(['2025-10', '2025-01'], dtype='datetime64[M]')

Passing it to pd.DatetimeIndex returns

In [32]: pd.DatetimeIndex(np.array(z1, dtype='datetime64[M]'))
Out[32]: DatetimeIndex(['2025-10-01', '2025-01-01'], dtype='datetime64[ns]', freq=None)
Sign up to request clarification or add additional context in comments.

2 Comments

The error using it with z1 is: TypeError: Cannot cast datetime.datetime object from metadata [us] to [M] according to the rule 'same_kind'. I am using Python 2.7
@Zanam: What version of NumPy are you using? You might be encountering this issue.
3

use date_range and set freq = 'MS'. The meaning of 'MS' can be interpreted from below

enter image description here

One line of code:

date_series = pd.date_range(start='1/1/2017', end ='12/1/2019', freq='MS')

Comments

2

You can first create Series from z1, then replace day and convert to date:

print (pd.DatetimeIndex(pd.Series(z1).apply(lambda x: x.replace(day=1)).dt.date))
DatetimeIndex(['2025-10-01', '2025-01-01'], dtype='datetime64[ns]', freq=None)

Another solution is convert day and hour:

print (pd.DatetimeIndex(pd.Series(z1).map(lambda x: x.replace(day=1, hour=0))))
DatetimeIndex(['2025-10-01', '2025-01-01'], dtype='datetime64[ns]', freq=None)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.