Skip to content
Advertisement

Is there a better way to increment a timestamp column in a pandas dataframe?

I’m working with a large pandas dataframe and want to add a timestamp column which correlates to the value of another column. For example, the current dataframe looks like this:

Server Hour
server1 0
server2 0
server1000 0
server1 1
server2 1

and so on, with the hours column at ranging from 0-167, as they correlate to the hourly timestamps of the following week.

I have the following code which establishes the weekly timestamps:

JavaScript

From there, I try to create the new “time” column arithmetically:

JavaScript

Then I convert the time column back to a string and convert the unix timestamp to datetime

JavaScript

Unfortunately, this method doesn’t use my current timezone and standardizes to UTC, so the finalized hourly timestamps are 4 hours ahead of where they should be. I can account for this by subtracting 4 hours before conversion, but I feel like there must be a cleaner way to do this using datetime. My solution seems like such a roundabout way to say “add however many hours are in the hour column.”

My expected output should look like this:

Server Hour Time
server1 0 2022-04-24 00:00:00-4:00
server2 0 2022-04-24 00:00:00-04:00
serverx 0 2022-04-24 00:00:00-04:00
server1000 0 2022-04-24 00:00:00-04:00
server1 1 2022-04-24 01:00:00-04:00
server2 1 2022-04-24 01:00:00-04:00
serverx 1 2022-04-24 01:00:00-04:00
server1000 1 2022-04-24 01:00:00-04:00
x x x
server1000 167 2022-04-30 23:00:00-04:00

with the “x” and “serverx” covering all of the server and hour values between 1 and 1000 and 1 and 167, respectively.

Alternatively, is there an easy way to convert between time zones? My current output column looks like it should, except it’s in UTC, and I’d like it in EST.

Advertisement

Answer

Do I understand correctly that you start out with a dataframe that has a hour column, for example:

JavaScript
JavaScript

In this case you could try the following:

JavaScript

Result:

JavaScript

Or use an explicit timezone offset:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement