Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

python - Rounding Pandas Timestamp to minutes

I want to create a DateTimeIndex at 1 minute intervals based on a start and end timestamp (given in microseconds since epoch) with pd_date_range(). To do this, I need to round the starting timestamp up and the ending timestamp down. Here is what I have so far:

import pandas as pd
start = 1406507532491431
end = 1406535228420914

start_ts = pd.to_datetime(start, unit='us') # Timestamp('2014-07-28 00:32:12.491431')
end_ts = pd.to_datetime(end, unit='us') # Timestamp('2014-07-28 08:13:48.420914')

I want to round:

start_ts to Timestamp('2014-07-28 00:32') and

end_ts to Timestamp('2014-07-28 08:14').

How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of version 0.18, Pandas has built-in datetime-like rounding functionality:

start_ts.round('min')  # Timestamp('2014-07-28 00:32:00')
end_ts.round('min')    # Timestamp('2014-07-28 08:14:00')

You can also use .ceil or .floor if you need to force the rounding up or down.


EDIT: The above code works with raw pd.Timestamp, as asked by the OP. In case you are working with a pd.Series, use the dt accessor:

s = pd.Series(pd.to_datetime([1406507532491431000, 1406535228420914000]))
s.dt.round('min')

Output:

0   2014-07-28 00:32:00
1   2014-07-28 08:14:00
dtype: datetime64[ns]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...