Rohit Rohit - 2 months ago 15
Python Question

Convert range to timestamp in Pandas

I have a column in a pandas data frame that goes from 0 to 172800000 in steps of 10. I would like to convert into datetime stamp with a specified date, beginning at midnight of that day.

So, suppose,

time = np.arange(0,172800000, 10)


I would like to convert this in the following format:

YYYY-MM-DD: HH:MM:SS.XXX


The starting date should be 2016-09-20.

Here's what I have done:

# Create a dummy frame as an example:
test = pd.DataFrame()
time = np.arange(0, 172800000, 10)
test['TIME'] = time
data = np.random.randint(0, 1000, size=len(time))
test['DATA'] = data

# Convert time to datetime:
test['TIME'] = pd.to_datetime(test['TIME'], unit='ms')


If I check the head of the data frame, I get the following:

TIME DATA
0 1970-01-01 00:00:00.000 681
1 1970-01-01 00:00:00.010 986
2 1970-01-01 00:00:00.020 957
3 1970-01-01 00:00:00.030 422
4 1970-01-01 00:00:00.040 319


How do I get the year, month, and day to start on 2016, 09, 20 and not 1970?

Answer

Try:

test['TIME'] = pd.to_datetime('2016-09-20') + pd.to_timedelta(time, 'ms')