Time stamped an hour out of sync

One thing I noticed is the csv files my code is creating are being time stamped an hour out of sync.

For example, when I save files at 18:44 my local time they are time stamped as 17:44.

I tried to run this to get around it


```

import pandas as pd

import pytz

from datetime import datetime, timedelta


# Adjust the offset

offset_hours = -6 # Mountain Time (UTC-6)


# Save the DataFrame df to 'eikon.csv' with an adjusted timestamp

output_file = 'eikon.csv'

timestamp = datetime.now() + timedelta(hours=offset_hours)

df.to_csv(output_file, index=False)

print(f"DataFrame saved to '{output_file}' with Mountain Time timestamp:", timestamp)


# Create the 'cam' DataFrame and save it to 'cam.csv'

cam_output_file = 'cam.csv'

cam_df = df[['TICKER', 'CAM']].copy()

cam_df.columns = ['ticker', 'cam']

cam_df.to_csv(cam_output_file, index=False)

print(f"'cam' DataFrame saved to '{cam_output_file}' with Mountain Time timestamp:", timestamp)


```


But it had no effect. I'm not seeing anything unusual in the logs or debugging console to indicate the cause of this.

This is not a major issue as it does not specifically affect my code, but it may have unforeseen effects on others, so I'm bringing it to your attention.

Best Answer

  • nick.zincone
    nick.zincone admin
    Answer ✓

    Hi @Jenan

    Instead of hard-coding the offset, try this:

    mountain_time = utc_time.astimezone(pytz.timezone("America/Denver"))

    Should be 7 hours difference MST and 6 MDT.

Answers

  • Jirapongse
    Jirapongse ✭✭✭✭✭

    @Jenan

    Thank you for reaching out to us.

    I ran the following code on CodeBook.

    from datetime import datetime, timedelta
    offset_hours = -6 # Mountain Time (UTC-6)
    now = datetime.now()
    timestamp = now + timedelta(hours=offset_hours)
    print(f"UTC:\t{now}")
    print(f"UTC-6:\t{timestamp}")

    The output is:

    1730276737765.png

    The value of timestamp is correct (UTC-6).