Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset time part of a pandas timestamp

Tags:

How can I reset the time part of a pandas timestamp?

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

  • step 1) Timestamp to datetime type
  • step 2) datetime to seconds
  • step 3) truncate time part in seconds
  • step 4) bring back seconds to Timestamp

Even if my guess is correct, it takes too long to do. Is there a straightforward way to achieve this goal?

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

In [372]: ts

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

In [373]: ts.hour = 0 # <-- this is what I am trying to do.

like image 987
Hill Avatar asked Nov 12 '14 08:11

Hill


People also ask

How do I change timestamp on pandas?

replace() function is used to replace the member values of the given Timestamp. The function implements datetime. replace, and it also handles nanoseconds.

How do I remove TZ from timestamp?

To remove timestamp, tzinfo has to be set None when calling replace() function. First, create a DateTime object with current time using datetime. now(). The DateTime object was then modified to contain the timezone information as well using the timezone.


2 Answers

I think you are looking for the 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 time part, you specify all 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 isn't available on the individual Timestamps (I opened an issue for that: https://github.com/pydata/pandas/issues/8794):

In [21]: pd.DatetimeIndex([ts]).normalize()[0] Out[21]: Timestamp('2014-11-12 00:00:00') 
like image 92
joris Avatar answered Sep 19 '22 13:09

joris


Instead of using datetime.datetime, use datetime.date and it will automatically truncate the hour/minute/second for you.

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

like image 27
twasbrillig Avatar answered Sep 20 '22 13:09

twasbrillig