Reset time part of pandas timestamp

How to reset pandas timestamp time part?

I want to reset part of the time in pandas.Timestamp value.
I think I can do this using the following procedure.

  • step 1) Timeline for date and time type
  • step 2) datetime to seconds
  • step 3) reduce the time in seconds
  • step 4) return seconds to timestamp

Even if my guess is correct, it takes too much time. Is there an easy way to achieve this?

In [371]: ts = pd.Timestamp ('2014/11/12 13:35')

In [372]: ts

Out [372]: time stamp ('2014-11-12 13:35:00')

In [373]: ts.hour = 0 # <is what I'm trying to do.

+8
python pandas datetime timestamp
Nov 12 '14 at 8:36
source share
4 answers

I think you are looking for a replace method (see docs ):

 In [18]: ts Out[18]: Timestamp('2014-11-12 13:35:00') In [19]: ts.replace(hour=0) Out[19]: Timestamp('2014-11-12 00:35:00') 

This is a method inherited from datetime.datetime

If you want to reset the full part of the time, you specify all the parts in replace :

 In [20]: ts.replace(hour=0, minute=0, second=0) Out[20]: Timestamp('2014-11-12 00:00:00') 

There is also a DatetimeIndex.normalize method, but this is not available for individual timestamps (I discovered a problem for it: https://github.com/pydata/pandas/issues/8794 ):

 In [21]: pd.DatetimeIndex([ts]).normalize()[0] Out[21]: Timestamp('2014-11-12 00:00:00') 
+15
Nov 12 '14 at 9:49
source share
— -

Instead of datetime.datetime use datetime.date and it will automatically clip hour / minute / second for you.

See https://docs.python.org/library/datetime.html#date-objects

0
Nov 12
source share
 pd.Timestamp('2014-11-12 13:35') - pd.offsets.Micro(0, normalize=True) == Timestamp('2014-11-12 00:00:00') 
0
Sep 27 '16 at 15:12
source share

Note that the replace method does not change the timestamp, so if you want to save the changed timestamp you must assign:

 In [2]: ts = pd.Timestamp('2014/11/12 13:35') In [3]: ts.replace(hour=0) Out[3]: Timestamp('2014-11-12 00:35:00') In [4]: ts Out[4]: Timestamp('2014-11-12 13:35:00') 

Note: ts does not change in the code above.

 In [5]: ts = ts.replace(hour=0) In [6]: ts Out[6]: Timestamp('2014-11-12 00:35:00') 
0
Oct 31 '17 at 10:25
source share



All Articles